PYTHON
Build Nested Dictionaries with `collections.defaultdict`
Learn to effortlessly create and populate nested dictionary structures in Python using `collections.defaultdict` to avoid `KeyError` exceptions.
from collections import defaultdict
# Example 1: Grouping items by category
items = [
{'name': 'Laptop', 'category': 'Electronics', 'price': 1200},
{'name': 'Keyboard', 'category': 'Electronics', 'price': 75},
{'name': 'Milk', 'category': 'Groceries', 'price': 3},
{'name': 'Bread', 'category': 'Groceries', 'price': 4}
]
grouped_by_category = defaultdict(list)
for item in items:
grouped_by_category[item['category']].append(item)
print(f"Grouped by category: {dict(grouped_by_category)}")
# Example 2: Counting events per user (nested defaultdict)
log_entries = [
{'user': 'Alice', 'event': 'login'},
{'user': 'Bob', 'event': 'login'},
{'user': 'Alice', 'event': 'logout'},
{'user': 'Alice', 'event': 'view_profile'},
]
user_event_counts = defaultdict(lambda: defaultdict(int))
for entry in log_entries:
user_event_counts[entry['user']][entry['event']] += 1
print(f"User event counts: {dict(user_event_counts)}")
How it works: This snippet demonstrates the power of `collections.defaultdict` for building complex, nested data structures without needing to explicitly check if a key exists before adding to it. When a key is accessed for the first time, `defaultdict` automatically creates a default value using the provided factory function (e.g., `list`, `int`, or even another `defaultdict`). This greatly simplifies code when aggregating data from various sources.