PYTHON
Grouping Items in a List of Dictionaries by a Common Key
Learn to efficiently group a list of dictionaries into a dictionary where keys are a common field from the original dictionaries and values are lists of corresponding items. Ideal for processing API results.
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': 'grape'}
]
# Group by 'category'
grouped_data = defaultdict(list)
for item in data:
grouped_data[item['category']].append(item)
# Convert defaultdict to a regular dict if needed
# print(dict(grouped_data))
# Expected output:
# {
# 'fruit': [
# {'id': 1, 'category': 'fruit', 'name': 'apple'},
# {'id': 3, 'category': 'fruit', 'name': 'banana'},
# {'id': 5, 'category': 'fruit', 'name': 'grape'}
# ],
# 'vegetable': [
# {'id': 2, 'category': 'vegetable', 'name': 'carrot'},
# {'id': 4, 'category': 'vegetable', 'name': 'broccoli'}
# ]
# }
How it works: This snippet demonstrates how to group a list of dictionaries based on the value of a specific key (e.g., 'category'). It uses `collections.defaultdict(list)`, which automatically creates an empty list for a key if it doesn't exist when you try to append to it, simplifying the grouping logic. This pattern is highly useful for organizing data retrieved from databases or APIs.