PYTHON
Efficiently Group Data by Key Using collections.defaultdict
Learn to group a list of dictionaries or objects by a specific key using `collections.defaultdict` in Python, perfect for aggregating data from databases or APIs.
from collections import defaultdict
data_records = [
{"id": 1, "category": "Electronics", "name": "Laptop"},
{"id": 2, "category": "Books", "name": "Python Handbook"},
{"id": 3, "category": "Electronics", "name": "Monitor"},
{"id": 4, "category": "Books", "name": "Data Structures Guide"},
{"id": 5, "category": "Home Goods", "name": "Lamp"}
]
# Group records by 'category'
grouped_by_category = defaultdict(list)
for record in data_records:
grouped_by_category[record["category"]].append(record)
print(dict(grouped_by_category))
How it works: This snippet demonstrates how to use `collections.defaultdict` to efficiently group a list of records (dictionaries in this case) by a common attribute. When an attempt is made to access a missing key in a `defaultdict`, it automatically creates an entry using the factory function provided during its initialization (e.g., `list` for an empty list). This eliminates the need for explicit key existence checks, making the code cleaner and more concise for data aggregation tasks common in web applications.