Grouping Data by Key with `collections.defaultdict`
Owner: SnippetBot
Created: 2026-09-23 00:00:32
Size: 1.11 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
from collections import defaultdict
# Example: Grouping orders by customer ID
orders = [
{"order_id": 101, "customer_id": "cust_A", "amount": 150.0},
{"order_id": 102, "customer_id": "cust_B", "amount": 200.0},
{"order_id": 103, "customer_id": "cust_A", "amount": 50.0},
{"order_id": 104, "customer_id": "cust_C", "amount": 300.0},
{"order_id": 105, "customer_id": "cust_B", "amount": 75.0},
]
orders_by_customer = defaultdict(list)
for order in orders:
orders_by_customer[order["customer_id"]].append(order)
print(f"Orders grouped by customer: {dict(orders_by_customer)}")
# Example 2: Grouping API endpoints by method
endpoints = [
{"path": "/users", "method": "GET", "handler": "get_users"},
{"path": "/users", "method": "POST", "handler": "create_user"},
{"path": "/products/{id}", "method": "GET", "handler": "get_product"},
{"path": "/users/{id}", "method": "DELETE", "handler": "delete_user"},
]
endpoints_by_method = defaultdict(list)
for ep in endpoints:
endpoints_by_method[ep["method"]].append(ep["path"])
print(f"Endpoints grouped by method: {dict(endpoints_by_method)}")