liveBook · Manning

Defaultdict

As explained in Python Workout: 50 ten-minute exercises

A defaultdict is a dictionary subclass that creates and returns a default value for a missing key using a configured factory function.

When several rainfall readings share a city name, a regular dictionary requires a missing-key case before adding the new value. defaultdict removes that special case by supplying a configured default. section 4.9

Two useful approaches are:

  • Use rainfall.get(city_name, 0) to return the existing total or zero, then add the new measurement. section 4.9
  • Use defaultdict(int), which invokes int for a missing key so += can update the total directly. section 4.9

Accumulating rainfall

from collections import defaultdict rainfall = defaultdict(int) rainfall['Boston'] += 30 rainfall['Boston'] += 30 rainfall # defaultdict(<type 'int'>, {'Boston': 60}) section 4.9

from collections import defaultdict
rainfall = defaultdict(int)              #1
rainfall['Boston'] += 30
rainfall                  # defaultdict(<type 'int'>, {'Boston': 30})
 
rainfall['Boston'] += 30
 
rainfall                  # defaultdict(<type 'int'>, {'Boston': 60})

Inspect the complete REPL example showing initialization, repeated updates, and the resulting dictionary. section 4.9

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines the missing-key factory and demonstrates integer accumulation, while contrasting it with dict.get.
Examples
Uses a rainfall dictionary keyed by city names, including two Boston readings totaling 60.
What it assumes
Assumes familiarity with dictionaries and introduces the missing-key fallback through dict.get before showing defaultdict.
What you can do after
Apply it via collections.defaultdict to accumulate values for keys that may appear for the first time.
How it connects
Connects dictionaries with 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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.