Grouping Data with collections.defaultdict
Owner: SnippetBot
Created: 2026-08-30 00:00:21
Size: 1.82 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from collections import defaultdict
def group_by_category(items):
"""Groups a list of items by their 'category' field.
Args:
items (list of dict): A list where each dictionary represents an item
and has a 'category' key.
Returns:
defaultdict: A dictionary where keys are categories and values are
lists of items belonging to that category.
"""
grouped_data = defaultdict(list) # Initialize with list as default factory
for item in items:
category = item.get('category', 'uncategorized') # Handle missing category gracefully
grouped_data[category].append(item)
return grouped_data
# Example Usage:
products = [
{'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200},
{'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75},
{'id': 3, 'name': 'Desk Chair', 'category': 'Furniture', 'price': 250},
{'id': 4, 'name': 'Monitor', 'category': 'Electronics', 'price': 300},
{'id': 5, 'name': 'Table', 'category': 'Furniture', 'price': 150},
{'id': 6, 'name': 'Mouse', 'category': 'Electronics', 'price': 25}
]
organized_products = group_by_category(products)
# organized_products will be:
# defaultdict(<class 'list'>, {
# 'Electronics': [
# {'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200},
# {'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75},
# {'id': 4, 'name': 'Monitor', 'category': 'Electronics', 'price': 300},
# {'id': 6, 'name': 'Mouse', 'category': 'Electronics', 'price': 25}
# ],
# 'Furniture': [
# {'id': 3, 'name': 'Desk Chair', 'category': 'Furniture', 'price': 250},
# {'id': 5, 'name': 'Table', 'category': 'Furniture', 'price': 150}
# ]
# })
print(organized_products['Electronics'])