A dictionary subclass that returns a default value for missing keys instead of raising a KeyError. See associative array — Wikipedia.
from collections import defaultdict
d = defaultdict(factory)The factory is any callable — list, int, lambda: None, etc. When a missing key is accessed, factory() is called to create the default value.
| Factory | Default value | Useful for |
|---|---|---|
list |
[] |
Grouping values by key |
int |
0 |
Counting occurrences |
lambda: None |
None |
Optional lookups |
python defaultdict.pyDemonstrates missing key handling, grouping words by first letter, and counting word frequency.