liveBook · Manning

Dict.setdefault

As explained in 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.

When accumulating scores by filename and subject, create each subject’s list only when needed, then append the score: scores[filename].setdefault(subject, []).append(score). The method preserves an existing list and supplies the default only for a missing key. section 6.23

Build nested score lists

For each parsed result, use the filename as the outer key and the subject as the inner key. Calling setdefault avoids a separate membership test before appending scores. section 6.23

scores[filename][subject]

Inspect the nested lookup expression used to reach the list for a particular filename and subject. section 6.23

if k not in d:
    d[k] = v

Compare setdefault with its explicit equivalent: test whether the key exists, assign the default when absent, and then use the value. section 6.23

How Python Workout, Second Edition covers it

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 it assumes
Assumes familiarity with dictionaries, lists, loops, and parsed JSON data structures.
What you can do after
Apply it via Python's dictionary API to build nested collections without a separate missing-key check.
How it connects
Connects dictionaries with lists, nested keys, JSON data, and dictionary iteration.

Also explained in

Compare how 2 books explain dict.setdefault →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.