Grouping records
Accumulate multiple values under each key without checking whether a list exists.
Python · Class
defaultdict is a dict subclass that creates and stores a value for an absent key by calling a configured zero-argument factory. It is useful for grouping, counting, and collecting distinct values without pre-initializing every key.
A defaultdict behaves like a dict but supplies a value for a missing key by calling its default_factory without arguments, storing that value under the key, and returning it. The factory is selected when the object is constructed and can also be changed later.
collections.defaultdict(default_factory=None, /, [...])| Name | Type | Description |
|---|---|---|
default_factory | callable | None | A callable invoked without arguments for an absent key, or None; it initializes default_factory. |
... | mapping or iterable, plus keyword arguments | Optional positional and keyword data accepted as by the dict constructor. |
A new dictionary-like object.
from collections import defaultdict
words = ["api", "db", "api", "cache"]
counts = defaultdict(int)
for word in words:
counts[word] += 1
print(dict(counts))A missing key starts at zero because int is the factory; incrementing then records each word's frequency.
Accumulate multiple values under each key without checking whether a list exists.
Increment per-key totals while unseen keys begin at zero.
Collect unique per-key values while automatically creating empty sets.
defaultdict is a dict subclass that adds the writable default_factory attribute and customizes missing-key handling. Other dict behavior remains the same.
Follow-up: What happens when the factory is None? A missing-key access raises KeyError with the requested key.
On a missing-key lookup, __missing__ calls default_factory with no arguments, inserts the returned value under that key, and returns it. If the factory is None, it raises KeyError.
Follow-up: Does get() use this behavior? No; get() follows normal-dict behavior and returns None unless an explicit default is supplied.
The first positional argument initializes default_factory, defaulting to None; remaining positional and keyword arguments are handled like dict construction. The factory must therefore be callable without arguments when used.
Follow-up: Can the factory be changed later? Yes, default_factory is a writable instance attribute, so assigning another callable changes subsequent missing-key behavior.
collections.Counterdict__missing__default_factory