PYTHON
Grouping Items by Key Using `collections.defaultdict`
Learn how to efficiently group items from a list of dictionaries into a dictionary of lists using Python's `collections.defaultdict` for cleaner code.
from collections import defaultdict
data = [
{'id': 1, 'category': 'A', 'value': 100},
{'id': 2, 'category': 'B', 'value': 200},
{'id': 3, 'category': 'A', 'value': 150},
{'id': 4, 'category': 'C', 'value': 300},
{'id': 5, 'category': 'B', 'value': 250},
]
grouped_data = defaultdict(list)
for item in data:
grouped_data[item['category']].append(item)
# Convert back to a regular dict if preferred, or use defaultdict directly
final_result = dict(grouped_data)
print(final_result)
# Expected output:
# {
# 'A': [{'id': 1, 'category': 'A', 'value': 100}, {'id': 3, 'category': 'A', 'value': 150}],
# 'B': [{'id': 2, 'category': 'B', 'value': 200}, {'id': 5, 'category': 'B', 'value': 250}],
# 'C': [{'id': 4, 'category': 'C', 'value': 300}]
# }
How it works: `collections.defaultdict` automatically provides a default value (e.g., an empty list) for any key accessed for the first time. This eliminates the need to check if a key exists before appending an item, making code cleaner and less verbose when grouping items.