Group Records with defaultdict
Core idea
defaultdict(factory) is a dict subclass. When bracket access misses a key, it calls the zero-argument factory, stores the returned value and returns it. Passing list as a factory makes a fresh empty list per missing key.
from collections import defaultdictgroups = defaultdict(list)for city, parcel in [("N", 4), ("S", 8), ("N", 9)]: groups[city].append(parcel)print(dict(groups))Each city receives its own list and parcel order is preserved.
Compare get and brackets
from collections import defaultdictcounts = defaultdict(int)print(counts.get("x"))print(len(counts))print(counts["x"], len(counts))get does not call the factory; bracket access creates the missing entry.
Use a configured factory
from collections import defaultdictlimits = defaultdict(lambda: 5)limits["A"] -= 2print(limits["A"], limits["B"])The lambda supplies an initial five for each missing key.
Common mistake
Pass list, not list(). Reading a missing key with brackets changes the mapping, so use get or membership when you only want to inspect it.
Practice
Group readings by station. Verify that appending to one station does not affect the other.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Default factories
Check your understanding of defaultdict.
What is printed?
from collections import defaultdictd = defaultdict(int)print(d.get("q"), len(d))What is printed?
from collections import defaultdictd = defaultdict(list)d["a"].append(4)print(d["a"], d["b"])Which exception occurs?
from collections import defaultdictdefaultdict([])Which operation can create a missing key by reading it?