collections.defaultdict & Missing Key Handlers
1Concept
`collections.defaultdict` overrides `__missing__(key)` to supply a default factory value (e.g. `list`, `int`, `set`) whenever a requested key does not exist, eliminating verbose `if key not in d:` checks.
2Architecture Diagram
d = defaultdict(list)
d['users'].append('Alice') ---> Creates empty list automatically if 'users' missing!3Code Example
Python 3.12
from collections import defaultdict
# Grouping items without KeyError
departments = [("Eng", "Alice"), ("Fin", "Bob"), ("Eng", "Charlie")]
grouped = defaultdict(list)
for dept, person in departments:
grouped[dept].append(person)
print(f"Grouped Employees: {dict(grouped)}")
print(f"Non-existent key access (empty list): {grouped['Marketing']}")4Expected Output
Grouped Employees: {'Eng': ['Alice', 'Charlie'], 'Fin': ['Bob']}
Non-existent key access (empty list): []5Key Takeaways
- ✓`defaultdict(int)` acts as a counter initializing missing keys to `0`.
- ✓Accessing a missing key automatically inserts it into the dictionary.
- ✓Use `lambda: default_val` for custom default factory values.