PYTHON
Simplify Dictionary Construction with `collections.defaultdict`
Learn to elegantly populate dictionaries without explicit key checks using Python's `collections.defaultdict`, perfect for grouping or building lists of values.
from collections import defaultdict
# Use a list as the default factory
grouped_data = defaultdict(list)
transactions = [
{'id': 1, 'category': 'food', 'amount': 25.50},
{'id': 2, 'category': 'transport', 'amount': 12.00},
{'id': 3, 'category': 'food', 'amount': 15.75},
{'id': 4, 'category': 'utilities', 'amount': 50.00},
{'id': 5, 'category': 'food', 'amount': 10.00},
]
for t in transactions:
grouped_data[t['category']].append(t)
# Accessing items (no KeyError if key doesn't exist, returns empty list)
food_items = grouped_data['food']
housing_items = grouped_data['housing'] # returns [], doesn't raise error
# Another example: counting with int as default factory
word_counts = defaultdict(int)
sentence = "hello world hello python"
for word in sentence.split():
word_counts[word] += 1
# Expected: defaultdict(<class 'int'>, {'hello': 2, 'world': 1, 'python': 1})
How it works: `collections.defaultdict` is a dictionary subclass that calls a factory function to supply missing values. It's particularly useful for initializing dictionary values with a default type (like `list` or `int`) when a key is accessed for the first time. This simplifies code for grouping items or counting frequencies, eliminating the need for explicit `if key not in dict` checks.