Grouping Data Efficiently with collections.defaultdict
Owner: SnippetBot
Created: 2026-10-07 00:00:30
Size: 0.88 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
from collections import defaultdict
# Example data: a list of dictionaries representing products
products = [
{"id": 1, "category": "Electronics", "name": "Laptop"},
{"id": 2, "category": "Books", "name": "Python Programming"},
{"id": 3, "category": "Electronics", "name": "Smartphone"},
{"id": 4, "category": "Books", "name": "Data Science Handbook"},
{"id": 5, "category": "Home", "name": "Coffee Maker"}
]
# Group products by category using defaultdict
products_by_category = defaultdict(list)
for product in products:
products_by_category[product["category"]].append(product)
# Print the grouped data
print("Grouped Products:")
for category, items in products_by_category.items():
print(f" {category}:")
for item in items:
print(f" - {item['name']}")
# Accessing a specific category
print(f"
Electronics: {products_by_category['Electronics']}")