liveBook · Manning

Dict.setdefault

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

When collecting scores by filename and subject, use dict.setdefault to create a missing list without replacing an existing one. It returns the value for the key, then lets the next operation append to that list. section 5.27

Build a nested score list

scores[filename].setdefault(subject, []) scores[filename][subject].append(score) The first line ensures that the subject key has a list. Repeated subjects keep their existing list, so each score can be appended during iteration. section 5.27

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

Compare setdefault with the explicit missing-key check it replaces: if k is not in d, assign d[k] = v. section 5.27

How Python Workout: 50 ten-minute exercises covers it

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 it assumes
Assumes familiarity with dictionaries, lists, loops, and appending values.
What you can do after
Apply dict.setdefault to accumulate values under keys without writing an explicit missing-key conditional.
How it connects
Connects dict.setdefault with dictionaries, lists, dict.items, JSON, and append operations.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.