PYTHON
Simplifying Dictionary Initialization for Grouping Data
Master collections.defaultdict in Python to effortlessly group data or aggregate values without explicit key existence checks, streamlining your code.
from collections import defaultdict
# Grouping by first letter
words = ["apple", "banana", "apricot", "berry", "cat"]
grouped_words = defaultdict(list)
for word in words:
grouped_words[word[0]].append(word)
print(f"Grouped words: {dict(grouped_words)}")
# Output: {'a': ['apple', 'apricot'], 'b': ['banana', 'berry'], 'c': ['cat']}
# Counting occurrences (similar to Counter, but showing defaultdict flexibility)
event_log = ["login", "logout", "login", "view_profile", "login"]
event_counts = defaultdict(int)
for event in event_log:
event_counts[event] += 1
print(f"Event counts: {dict(event_counts)}")
# Output: {'login': 3, 'logout': 1, 'view_profile': 1}
# Nested defaultdict for complex structures
nested_data = defaultdict(lambda: defaultdict(int))
sales_data = [
("2023-01-01", "productA", 100),
("2023-01-01", "productB", 50),
("2023-01-02", "productA", 75),
]
for date, product, sales in sales_data:
nested_data[date][product] += sales
print(f"Nested sales data: {dict(nested_data)}")
How it works: collections.defaultdict is a dictionary subclass that calls a factory function (e.g., list, int, set) to supply missing values when a key is accessed for the first time. This eliminates the need for explicit if key not in dict: checks, making code cleaner and more concise for grouping or aggregating data, especially in web contexts where data often needs categorization.