PYTHON
Simplify Dictionary Grouping with Python's collections.defaultdict
Discover how collections.defaultdict simplifies dictionary operations by automatically providing a default value for missing keys, perfect for grouping items without explicit key checks.
from collections import defaultdict
# Grouping items by a property
data = [
{"name": "Alice", "city": "New York"},
{"name": "Bob", "city": "London"},
{"name": "Charlie", "city": "New York"},
{"name": "David", "city": "London"},
]
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item["city"]].append(item["name"])
print(f"Grouped by city: {dict(grouped_by_city)}")
# Counting occurrences
word_list = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_counts = defaultdict(int)
for word in word_list:
word_counts[word] += 1
print(f"Word counts: {dict(word_counts)}")
How it works: collections.defaultdict is a subclass of dict that overrides one method: __missing__. When you try to access a key that isn't present, defaultdict automatically inserts a default value created by its factory function (e.g., list for an empty list, int for 0) before returning it. This eliminates the need for boilerplate `if key not in dict:` checks, making code cleaner and more concise for tasks like grouping items or counting frequencies.