PythiloLesson 4 of 8 · progress kept in this browser

Aggregate an iterator in one pass

A data source may be a generator that cannot be restarted. Accumulate only the state required for the answer rather than converting every row into a list. For totals by category, a dictionary needs one value per distinct category. This keeps memory tied to the number of groups rather than the number of records.

from collections import defaultdict
totals = defaultdict(int)
totals["books"] += 3
print(dict(totals))
Your task

Write totals_by_key(rows). Consume an iterable of (key, amount) pairs exactly once and return a plain dict of totals. Include zero totals and support negative amounts.