PYTHON
Group Data by Key Using `defaultdict`
Effectively group a list of dictionaries or objects by a common key into a dictionary of lists using Python's `collections.defaultdict`.
from collections import defaultdict
products = [
{'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 Illustrated'},
]
# Group products by category
products_by_category = defaultdict(list)
for product in products:
products_by_category[product['category']].append(product)
print(products_by_category)
# Output: defaultdict(<class 'list'>, {'Electronics': [{'id': 1, 'category': 'Electronics', 'name': 'Laptop'}, {'id': 3, 'category': 'Electronics', 'name': 'Monitor'}], 'Books': [{'id': 2, 'category': 'Books', 'name': 'Python Handbook'}, {'id': 4, 'category': 'Books', 'name': 'Data Structures Illustrated'}]})
How it works: The `collections.defaultdict` is a powerful way to group items. When you try to access a key that doesn't exist, it automatically creates an entry using the default factory (here, `list`), allowing you to directly append items without explicitly checking for key existence. This simplifies common data aggregation tasks in web backends, such as organizing fetched database records or API responses by a common attribute.