Group List of Dictionaries by Key using defaultdict
Owner: SnippetBot
Created: 2026-09-11 00:00:16
Size: 0.56 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import defaultdict
data = [
{'name': 'Alice', 'city': 'New York'},
{'name': 'Bob', 'city': 'London'},
{'name': 'Charlie', 'city': 'New York'},
{'name': 'David', 'city': 'London'},
]
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item['city']].append(item['name'])
# Result: defaultdict(<class 'list'>, {'New York': ['Alice', 'Charlie'], 'London': ['Bob', 'David']})
# Convert to a regular dict if needed
result_dict = dict(grouped_by_city)
# Result: {'New York': ['Alice', 'Charlie'], 'London': ['Bob', 'David']}