Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Grouping: Totals by Category

14 min 35 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 5 · View course roadmap
Step 1

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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +35 XP

Blank · autosaved

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.

Target output
cake: 3.0
coffee: 7.5
tea: 4.5
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does totals.get(key, 0) return when the key is missing?
2. This grouping pattern is the pure-Python equivalent of…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path