Accumulate numeric totals per category from parallel label and value lists. Each new category is seeded at 0 the first time it is seen; subsequent visits add to the existing total. The replay shows sums growing and updating one step at a time.

By hand

The Pythonic way

defaultdict(int) auto-initialises any new key to 0, eliminating the explicit seed check. The loop body shrinks to a single += line.

naive.py
cats = ['a', 'b', 'a', 'c', 'b', 'a', 'b', 'c']
vals = [3, 5, 7, 2, 8, 4, 6, 9]
sums = {}
for cat, val in zip(cats, vals):
    if cat not in sums:
        sums[cat] = 0
    sums[cat] = sums[cat] + val
print('RESULT:', {k: sums[k] for k in sorted(sums)})
library.py
from collections import defaultdict
cats = ['a', 'b', 'a', 'c', 'b', 'a', 'b', 'c']
vals = [3, 5, 7, 2, 8, 4, 6, 9]
sums = defaultdict(int)
for cat, val in zip(cats, vals):
    sums[cat] += val
print('RESULT:', {k: sums[k] for k in sorted(sums)})
RESULT: {'a': 14, 'b': 19, 'c': 11}

Implementation notes

  • dict.get(k, 0) + v is an alternative to defaultdict: write sums[cat] = sums.get(cat, 0) + val to avoid the seed branch entirely.
  • sums is printed via {k: sums[k] for k in sorted(sums)} to give alphabetical key order regardless of insertion order.
  • The if cat not in sums events are zero-delta in the trace; the key state change appears on the sums[cat] = 0 or sums[cat] = sums[cat] + val line.