SypherTec
…
PART 3 · 03 OF 084 MIN READUPDATED 20 NOV 2026

Looping Over Dictionaries: Totals per Category

Your expenses each carry a category now, but your report never adds them up by category. This lesson totals your spending per category and checks each total against its budget.

The concept

Here is your tracker as the last lesson left it. Run it:

WHERE YOU LEFT OFF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Start with the budgets you already have. Run this:

EVERY KEY WITH ITS VALUE · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Three categories, each with its budget, from one print. The loop has two names. On each pass, category holds a key and limit holds its value.

That is .items(): a dictionary method that hands a loop the keys and values together, one pair per pass.

Now build a dictionary inside a loop, with a total per category. Run this:

A TOTAL PER CATEGORY, PASS BY PASS · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

category_totals started as {}, an empty dictionary. The print sits inside the loop, so you see the dictionary after every pass.

  • Pass one: Bus fare is transport, a new key, so the else created it with 1500.
  • Pass two: Lunch is food, also new, so the else created it with 2500.
  • Pass three: Suya is food too. That key was there, so the if added 800 to it, making 3300.

This is the accumulator pattern with one accumulator per key, a pattern called grouping.

The syntax

for category, limit in category_budgets.items():
    print(f"{category}: ₦{limit:,}")
  • .items() goes after the dictionary's name: a dot, items, and empty parentheses.
  • Two loop names, separated by a comma. The first holds the key, the second its value. You choose both names.
  • The pairs come in the order the keys were added.

Grouping follows the three accumulator parts you already know:

category_totals = {}
for record in expenses:
    category = record["category"]
    if category in category_totals:
        category_totals[category] = category_totals[category] + record["amount"]
    else:
        category_totals[category] = record["amount"]
  1. Start with an empty dictionary, before the loop.
  2. Update it inside the loop. If the category is already a key, add this amount to its total. If not, create the key with this amount.
  3. Read it after the loop, with .items().

A minimal working example

main.py
expenses = [
    {"item": "Bus fare", "category": "transport", "amount": 1500},
    {"item": "Lunch", "category": "food", "amount": 2500},
    {"item": "Suya", "category": "food", "amount": 800},
]
 
category_totals = {}
for record in expenses:
    category = record["category"]
    if category in category_totals:
        category_totals[category] = category_totals[category] + record["amount"]
    else:
        category_totals[category] = record["amount"]
 
for category, spent in category_totals.items():
    print(f"{category}: ₦{spent:,}")

Output: transport: ₦1,500, then food: ₦3,300. A record with a new category gets a key of its own. You never list the categories yourself.

Common mistakes

You loop with two names but forget .items(). Run this:

TWO NAMES WITHOUT .ITEMS() · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output
ValueError: too many values to unpack (expected 2)

Without .items(), a loop over a dictionary gives only its keys. Python tried to share the first key, "food", across your two names, one letter each. Four letters are too many for two names. Add .items() after the dictionary's name.

You loop with one name and expect the values. Run this:

ONE NAME, EXPECTING THE VALUES · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

No error, but the category names printed, not the budgets. Naming the loop variable limit does not change what it holds. For the values too, use .items() with two names.

You add to a key before it exists. Run this:

ADDING TO A TOTAL THAT DOES NOT EXIST YET · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output
KeyError: 'transport'

On the first pass, category_totals was still empty. The right side of the = asked for the total under "transport", which did not exist yet. That is why grouping needs its if and else.

Your report gives the same error if an expense's category has no entry in category_budgets. Give every category you spend in a budget.

Try it yourself

You will total your spending per category, and check each total against its budget.

  1. Run the starting code below. Confirm your report has a Categories budgeted line and a Food budget line under Budget.

  2. Under your large_spends = count_over(amounts, 3000) line, with no indentation, add the grouping loop:

    category_totals = {}
    for record in expenses:
        category = record["category"]
        if category in category_totals:
            category_totals[category] = category_totals[category] + record["amount"]
        else:
            category_totals[category] = record["amount"]

    Run it. Confirm your report has not changed and shows no error. The totals exist, but nothing prints them yet.

  3. Find the line that prints Status: within budget, the last line of your status if/elif/else. Directly under it, with no indentation, add:

    print()
    print("By category:")
    for category, spent in category_totals.items():
        limit = category_budgets[category]
        print(f"  {category}: ₦{spent:,} of ₦{limit:,}")

    Run it. Confirm a By category: section appears under your status, with one line per category you spent in. With the expenses given, those are transport, food and data. A category with no spending does not appear, because the loop goes through category_totals.

  4. Mark the categories that went over. Replace the print inside your new loop with this if/else, indented four spaces to stay inside the loop:

        if spent > limit:
            print(f"  {category}: ₦{spent:,} of ₦{limit:,}, over")
        else:
            print(f"  {category}: ₦{spent:,} of ₦{limit:,}")

    Run it. Confirm every category that spent more than its budget now ends with , over. With the expenses given, those are transport and data.

  5. Your new section replaces the two old category lines. Under print_line("Budget", budget), delete the line that prints Categories budgeted and the print_line for Food budget. Run it. Confirm both lines are gone from your report.

  6. Break it on purpose: in your grouping loop, select the four lines from if category in category_totals: down to category_totals[category] = record["amount"]. Replace them with this one line, indented four spaces:

        category_totals[category] = category_totals[category] + record["amount"]

    Run it. Confirm nothing from your report prints, and the console shows a KeyError naming the category of your first expense. With the expenses given, that is KeyError: 'transport'.

  7. Fix it: put the four if/else lines from step 2 back in place of that one line, indented as they were. Run it. Confirm your full report returns, with the By category: section above your savings line.

TRY IT YOURSELF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Your tracker now totals each category and flags the ones over budget. Every record is still typed by hand, though. The next lesson reads your expenses from lines of text instead, the way a receipt lists them.

QUIZ · 3 QUESTIONSCheck what stuckStart the quiz
PART 3 · 03 OF 08❮❯