PYTHON
Group Objects by a Common Attribute Using `itertools.groupby`
Discover how to efficiently group a list of dictionaries or objects by a shared attribute using `itertools.groupby` for structured data processing.
from itertools import groupby
from operator import itemgetter
data = [
{'id': 1, 'category': 'Electronics', 'value': 10},
{'id': 2, 'category': 'Books', 'value': 20},
{'id': 3, 'category': 'Electronics', 'value': 15},
{'id': 4, 'category': 'Home', 'value': 25},
{'id': 5, 'category': 'Books', 'value': 30}
]
# CRITICAL: Sort data by the grouping key first for groupby to work correctly
data.sort(key=itemgetter('category'))
grouped_data = {}
for key, group in groupby(data, itemgetter('category')):
grouped_data[key] = list(group)
print(grouped_data)
How it works: This snippet illustrates how to group a list of dictionaries by a common key (e.g., 'category') using `itertools.groupby`. It's crucial to sort the data by the grouping key *before* calling `groupby`, as `groupby` only groups consecutive identical elements. The `itemgetter` function from the `operator` module provides an efficient way to extract the key for sorting and grouping, which is very common for structuring API responses or database query results.