PYTHON
Group Items by Category Using `collections.defaultdict`
Organize items into categories by efficiently grouping them into a dictionary where keys are categories and values are lists of items using Python's `collections.defaultdict`.
from collections import defaultdict
data = [
{'name': 'Apple', 'category': 'Fruit'},
{'name': 'Banana', 'category': 'Fruit'},
{'name': 'Carrot', 'category': 'Vegetable'},
{'name': 'Broccoli', 'category': 'Vegetable'},
{'name': 'Orange', 'category': 'Fruit'}
]
# Using defaultdict to group items
grouped_data = defaultdict(list)
for item in data:
category = item['category']
group_list = grouped_data[category] # If category not present, a new empty list is created
group_list.append(item['name'])
print(f"Grouped data: {dict(grouped_data)}")
# Example with another type (e.g., int for counting)
counted_items = defaultdict(int)
numbers = [1, 2, 2, 3, 3, 3, 1]
for num in numbers:
counted_items[num] += 1
print(f"Counted items: {dict(counted_items)}")
How it works: `collections.defaultdict` is incredibly useful for grouping data. When you access a key that doesn't exist in a `defaultdict`, it automatically inserts a default value created by the callable factory provided during initialization (e.g., `list` for an empty list, `int` for zero). This eliminates the need for explicit `if key not in dict:` checks, making the code cleaner and less error-prone. In this snippet, items are grouped by their 'category' into lists, and numbers are counted by their value.