defaultdict Grows Nested Groups On Demand

Group records without missing-key guards: nested defaultdict(int) totals build buckets on first touch, and a list factory collects failures in arrival order.

PythonData Integrity

Code

pythonsnippet
31 lines
from collections import defaultdict

# 工厂在首次访问时自动建值,分组不再需要 "键不存在" 的前置判断
sales = [
    ("emea", "subscriptions", 1200),
    ("apac", "services", 800),
    ("emea", "services", 450),
    ("apac", "subscriptions", 990),
]

totals = defaultdict(lambda: defaultdict(int))
for region, product, amount in sales:
    totals[region][product] += amount

for region in sorted(totals):
    for product, amount in sorted(totals[region].items()):
        print(f"{region:5s} {product:14s} {amount}")

# defaultdict 就是 dict:需要普通字典时直接 dict() 转换
print("apac as plain dict:", dict(totals["apac"]))

# list 工厂按到达顺序收集成员:失败产品按 region 归组
failures = defaultdict(list)
for region, product, ok in [
    ("emea", "subscriptions", True),
    ("emea", "services", False),
    ("apac", "services", True),
]:
    if not ok:
        failures[region].append(product)
print("failed products by region:", dict(failures))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

apac  services       800
apac  subscriptions  990
emea  services       450
emea  subscriptions  1200
apac as plain dict: {'services': 800, 'subscriptions': 990}
failed products by region: {'emea': ['services']}

Inside the snippet

Iteration happens inside for region, product, amount in sales — everything outside it runs once.

Everything operates on top-level bindings: sales, totals, failures.

Where this earns its keep

The demo output is labeled (apac as plain dict:, failed products by region:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `collections`. Its state lives in module-level bindings: `sales`, `totals`, `failures`.