`defaultdict`
collections.defaultdict is a dict that calls a factory for missing keys instead of raising KeyError. defaultdict(list) is the usual way to group items.
Detailed Explanation
table[key].append(item) fails on the first unseen key. The older fix is table.setdefault(key, []).append(item), which works and creates an empty list even if you only meant to peek. defaultdict(list) makes the factory implicit: a missing key is replaced by list() and then stored.
The argument is a zero-argument callable. list, set, int, and lambda: {"count": 0} are typical. int is handy for counters (scores[name] += 1) though Counter is clearer for that specific job. defaultdict(dict) builds a two-level map.
The factory runs on read of a missing key, not only on assignment. if missing in table does not insert. table[missing] does. table.get(missing) does not; get is inherited and does not use the factory. That split surprises people who debug with print(table[key]) and then wonder why the key appeared.
defaultdict is a dict subclass. It pickles, copies, and iterates like a dict. default_factory is an attribute you can set to None to disable auto-insert (further missing reads raise KeyError).
Use it for grouping, adjacency lists, and nested accumulators. Do not use it when a missing key is an error you must see. A plain dict plus KeyError is the right API for "this id must already exist".
A factory that returns a shared mutable (defaultdict(lambda: shared_list)) shares that object among all missing keys. Use list, not a single prebuilt list.
Code Examples
from collections import defaultdict
orders = [("ada", "A-1"), ("ada", "B-2"), ("linus", "A-1")]
by_user = defaultdict(list)
for user, sku in orders:
by_user[user].append(sku)
print(dict(by_user))
# {'ada': ['A-1', 'B-2'], 'linus': ['A-1']}graph = defaultdict(set)
graph["a"].add("b")
graph["a"].add("c")
print(graph["a"]) # {'b', 'c'}
print("z" in graph) # False, membership does not insert
print(graph["z"]) # set() <- read inserted an empty set
print("z" in graph) # True# int factory for tallies. Counter is clearer if that is all you need.
hits = defaultdict(int)
for path in ["/", "/", "/about"]:
hits[path] += 1
print(hits["/"], hits["/missing"]) # 2 0 <- /missing was inserted as 0Common Gotchas
Indexing a missing key inserts it
`print(table[k])` while debugging changes the table. Use `k in table` or `table.get(k)`.
`get` does not call the factory
`table.get(k)` returns `None` for a missing key, not `list()`.
A factory must take no arguments
`defaultdict([])` raises `TypeError` because a list is not callable. Pass `list`.
`setdefault` on a plain dict is enough for one-off grouping
`defaultdict` is for a map that stays in that pattern.