PYTHON
Efficiently Group Data by Key with `defaultdict`
Learn how to quickly group a list of dictionaries or objects by a common key using Python's `collections.defaultdict`, perfect for processing API responses.
from collections import defaultdict
data = [
{"id": 1, "category": "fruit", "name": "Apple"},
{"id": 2, "category": "vegetable", "name": "Carrot"},
{"id": 3, "category": "fruit", "name": "Banana"},
{"id": 4, "category": "vegetable", "name": "Broccoli"},
{"id": 5, "category": "fruit", "name": "Orange"},
]
# Group items by 'category'
grouped_data = defaultdict(list)
for item in data:
grouped_data[item["category"]].append(item)
# Convert defaultdict to a regular dict for final output if needed
final_grouped_data = dict(grouped_data)
print(final_grouped_data)
How it works: This snippet demonstrates how to use `collections.defaultdict` to efficiently group items from a list of dictionaries based on a specified key. When a key is accessed for the first time, `defaultdict(list)` automatically initializes an empty list, preventing `KeyError` and simplifying the grouping logic compared to a regular dictionary. The result is a dictionary where keys are the categories and values are lists of items belonging to that category.