PYTHON
Simplifying Dictionary Initializations with `collections.defaultdict`
Discover how `collections.defaultdict` automatically initializes dictionary values, simplifying code for grouping items or accumulating data without explicit `if` checks.
from collections import defaultdict
# Example 1: Grouping items into lists
data = [('fruit', 'apple'), ('vegetable', 'carrot'), ('fruit', 'banana'), ('vegetable', 'broccoli')]
grouped_by_type = defaultdict(list)
for category, item in data:
grouped_by_type[category].append(item)
print("Grouped by type:", dict(grouped_by_type))
# Example 2: Counting occurrences
word_list = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_counts = defaultdict(int) # Default value for int is 0
for word in word_list:
word_counts[word] += 1
print("Word counts:", dict(word_counts))
How it works: `collections.defaultdict` is a dictionary subclass that calls a factory function to supply missing values. When you try to access a key that isn't present, `defaultdict` automatically creates it and assigns a default value (e.g., an empty list for `list`, 0 for `int`) instead of raising a `KeyError`. This simplifies code for tasks like grouping items into lists or sets, or counting occurrences, by eliminating the need for explicit checks if a key exists before adding to its value.