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))Think before coding
The dictionary is sufficient state for a single-pass reduction. Iterating directly supports generators and large sources. Negative adjustments use the same addition rule as positive amounts. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
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.
The explanation opens here once every check passes.