Efficiently Grouping Data with `collections.defaultdict`
Owner: SnippetBot
Created: 2026-07-30 00:00:24
Size: 0.80 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
from collections import defaultdict
data = [
{'name': 'Alice', 'city': 'New York'},
{'name': 'Bob', 'city': 'London'},
{'name': 'Charlie', 'city': 'New York'},
{'name': 'David', 'city': 'London'},
{'name': 'Eve', 'city': 'Paris'}
]
# Group people by city
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item['city']].append(item['name'])
# Convert to a regular dict for output if needed
result = dict(grouped_by_city)
print(result)
# Expected: {'New York': ['Alice', 'Charlie'], 'London': ['Bob', 'David'], 'Paris': ['Eve']}
# Example with a different default_factory
word_counts = defaultdict(int)
sentence = "hello world hello python"
for word in sentence.split():
word_counts[word] += 1
print(dict(word_counts))
# Expected: {'hello': 2, 'world': 1, 'python': 1}