Group items by a key

Turn a flat list into a dict of lists with collections.defaultdict.

python beginner #collections#dict#data
Ouvrir dans le playground
python-group-by.py
from collections import defaultdict

orders = [
    {"customer": "ada", "total": 30},
    {"customer": "linus", "total": 12},
    {"customer": "ada", "total": 8},
]

by_customer = defaultdict(list)
for order in orders:
    by_customer[order["customer"]].append(order)

totals = {name: sum(o["total"] for o in items) for name, items in by_customer.items()}
print(dict(by_customer))
print(totals)   # {'ada': 38, 'linus': 12}