Grouping: Totals by Category
Lesson 3 of 5 · View course roadmap
Learn the idea
"Revenue by product", "signups by country", "errors by endpoint" — the words by category always mean the same code: accumulate into a dictionary.
totals[key] = totals.get(key, 0) + value— the one-line accumulator: start at 0 if the key is new, add if it exists- Loop the pairs once; the dict grows itself
sorted(totals.items())— report in a stable, readable order
This is the pure-Python version of SQL's GROUP BY and pandas' groupby() — learn the pattern here and those tools will feel obvious later.
Where you'll use this
GROUP BY in SQL, groupby() in pandas, pivot tables in Excel — the dict accumulator is the same operation with the curtain pulled back. Understanding it here means those tools become syntax, not magic.
Common mistakes
- totals[key] += value without initialising → KeyError on the first sighting of each key. Use .get(key, 0) or defaultdict.
- Assuming dict iteration order is sorted — it's insertion order. Sort explicitly when reporting.
- Accumulating floats and being surprised by 0.30000000000000004 — round at display time, not during accumulation.
Pro tip
from collections import defaultdict; totals = defaultdict(float) removes the .get dance entirely: totals[key] += value just works.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
Total the sales per product in sales = [("coffee", 3.5), ("tea", 2.0), ("coffee", 4.0), ("cake", 3.0), ("tea", 2.5)] and print one line per product in alphabetical order, formatted product: total.
cake: 3.0 coffee: 7.5 tea: 4.5
for product, amount in sales: totals[product] = totals.get(product, 0) + amount. Then loop sorted(totals.items()).
sales = [("coffee", 3.5), ("tea", 2.0), ("coffee", 4.0), ("cake", 3.0), ("tea", 2.5)]
totals = {}
for product, amount in sales:
totals[product] = totals.get(product, 0) + amount
for product, total in sorted(totals.items()):
print(f"{product}: {total}")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.