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:
Start with the budgets you already have. Run this:
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:
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 theelsecreated it with1500. - Pass two: Lunch is
food, also new, so theelsecreated it with2500. - Pass three: Suya is
foodtoo. That key was there, so theifadded800to it, making3300.
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"]- Start with an empty dictionary, before the loop.
- 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.
- Read it after the loop, with
.items().
A minimal working example
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:
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:
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:
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.
-
Run the starting code below. Confirm your report has a
Categories budgetedline and aFood budgetline underBudget. -
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.
-
Find the line that prints
Status: within budget, the last line of your statusif/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 throughcategory_totals. -
Mark the categories that went over. Replace the
printinside your new loop with thisif/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. -
Your new section replaces the two old category lines. Under
print_line("Budget", budget), delete the line that printsCategories budgetedand theprint_lineforFood budget. Run it. Confirm both lines are gone from your report. -
Break it on purpose: in your grouping loop, select the four lines from
if category in category_totals:down tocategory_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
KeyErrornaming the category of your first expense. With the expenses given, that isKeyError: 'transport'. -
Fix it: put the four
if/elselines from step 2 back in place of that one line, indented as they were. Run it. Confirm your full report returns, with theBy category:section above your savings line.
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.