liveBook · Manning

Dict.setdefault

dict.setdefault is a Python dictionary method that returns a key’s value, inserting the key with a specified default value if it is absent.

How 2 Manning books explain it

Python Workout: 50 ten-minute exercises

dict.setdefault is a dictionary method that returns a key's value and inserts the key with a default value when the key is absent.

How it is used
Groups scores into lists while processing unknown subjects and an unknown number of tests.
How deep it goes
Defines conditional assignment through a nested score-collection example, but does not examine method internals.
Examples
Uses a nested scores dictionary keyed by filename and subject, with lists storing scores.
What you can do after
Apply dict.setdefault to accumulate values under keys without writing an explicit missing-key conditional.

Read how Python Workout: 50 ten-minute exercises explains dict.setdefault →

Python Workout, Second Edition

dict.setdefault is a dictionary method that returns a key's value and inserts the key with a default value when the key is absent.

How it is used
Uses conditional dictionary insertion to accumulate scores under previously unknown filename and subject keys.
How deep it goes
Explains conditional key creation and list accumulation, but does not descend into method internals.
Examples
Uses a nested scores dictionary keyed by filename and subject, with lists storing multiple test scores.
What you can do after
Apply it via Python's dictionary API to build nested collections without a separate missing-key check.

Read how Python Workout, Second Edition explains dict.setdefault →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.