liveBook · Manning

Defaultdict

As explained in Python Workout, Second Edition

defaultdict is a collections class that supplies a default value for missing dictionary keys by calling a configured factory.

Use defaultdict when repeated updates must create a missing dictionary entry automatically. It behaves like a regular dict until a missing key is requested, then calls its configured factory. section 5.9

Accumulating rainfall

from collections import defaultdict rainfall = defaultdict(int) rainfall['Boston'] += 30 rainfall['Boston'] += 30 # rainfall contains {'Boston': 60} The int factory supplies 0 for the first missing lookup, allowing += to proceed without an explicit initialization. section 5.9

from collections import defaultdict
rainfall = defaultdict(int)       #1
rainfall['Boston'] += 30
rainfall            #2

rainfall['Boston'] += 30

rainfall           #3

Inspect the executable defaultdict pattern for initializing and incrementing a rainfall mapping. section 5.9

How Python Workout, Second Edition covers it

How deep it goes
Explains factory invocation and demonstrates integer accumulation, while stopping short of broader factory choices.
Examples
Uses a rainfall dictionary, repeated Boston entries, and defaultdict(int) to accumulate millimeters.
What it assumes
Assumes familiarity with dictionaries and introduces dict.get as an alternative missing-key strategy.
What you can do after
Apply it via collections.defaultdict to accumulate values without manually initializing missing keys.
How it connects
Connects defaultdict with dictionaries, dict.get, and the collections module.

Also explained in

Compare how 3 books explain defaultdict →

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.