Efficiently Grouping Data by a Key with `itertools.groupby`
Owner: SnippetBot
Created: 2026-08-18 00:00:25
Size: 0.83 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from itertools import groupby
# Sample data (must be sorted by the key you want to group by)
data = [
{'name': 'Alice', 'city': 'New York'},
{'name': 'Bob', 'city': 'London'},
{'name': 'Charlie', 'city': 'New York'},
{'name': 'David', 'city': 'London'},
{'name': 'Eve', 'city': 'Paris'}
]
# Sort the data by 'city' for groupby to work correctly
data.sort(key=lambda x: x['city'])
print(f"Sorted data: {data}
")
grouped_by_city = {}
for city, group in groupby(data, key=lambda x: x['city']):
grouped_by_city[city] = list(group) # Convert group iterator to a list
print(f"Grouped by city: {grouped_by_city}")
# Example of printing groups more clearly
print("
--- Grouped Output ---")
for city, group_items in grouped_by_city.items():
print(f"City: {city}")
for item in group_items:
print(f" - {item['name']}")