Your tracker has one budget for the whole month. Real spending splits into food, transport, data and more, and each part needs a limit of its own. This lesson stores a budget for each category under the category's name, so your program can look one up.
The concept
Here is your tracker at the end of Part 2. Run it:
One Budget line covers everything you spend. Now run this:
You asked for "food" and got 6000. You asked for "transport" and got 4000. Each amount is stored under a name, and you get it back by asking for that name. A value that stores pairs like this is a dictionary. The name in each pair is called its key. The amount stored under it is that key's value.
The contacts on your phone work the same way. You find a number by searching for a name, not by counting down to the seventh entry.
Compare a list. In budgets = [6000, 4000, 3000, 2000], the food budget is budgets[0]. You have to remember that food sits at position 0, and nothing in the code says so. A list finds an item by its position. A dictionary finds a value by its key, so category_budgets["food"] says what it means.
A dictionary can change after you create it:
category_budgets["data"] = 3000 added a new pair, because there was no "data" key yet. category_budgets["food"] = 7000 replaced the food budget, because a dictionary holds each key only once. The same kind of line adds or updates, depending on whether the key is already there. Then len counted the pairs: 3.
When Python prints a whole dictionary, it shows the keys in single quotes. That is only how it displays text. 'food' and "food" are the same key.
You can also ask whether a key is there:
"data" in category_budgets asks whether "data" is one of the keys. Like a comparison, it gives back True or False. The last line printed False because a key must match exactly. "Food" with a capital F is a different string from "food", so it is a different key.
The syntax
category_budgets = {"food": 6000, "transport": 4000}- Curly braces hold the pairs.
- Each pair is a key, a colon, then the value.
- A comma separates each pair from the next.
- These keys are text, so they need quotes. The values are numbers.
food_budget = category_budgets["food"]
category_budgets["data"] = 3000
category_budgets["food"] = 7000
count = len(category_budgets)
has_fuel = "fuel" in category_budgetscategory_budgets["food"]gives back the value stored under the key"food". The square brackets are the same as a list's, with a key inside instead of a position.- Assigning to a new key adds a pair. Assigning to a key that is already there replaces its value.
len(category_budgets)gives back the number of pairs."fuel" in category_budgetsgives backTruewhen"fuel"is a key, andFalsewhen it is not. It checks the keys, not the values.- This
inasks a question. Theinon aforline belongs to the loop and does a different job.
Because in answers True or False, it fits into an if. Checking first means you never ask for a key that is not there:
if "fuel" in category_budgets:
print_line("Fuel budget", category_budgets["fuel"])
else:
print("No fuel budget yet")A minimal working example
category_budgets = {"food": 6000, "transport": 4000, "data": 3000}
category_budgets["other"] = 2000
count = len(category_budgets)
food_budget = category_budgets["food"]
has_fuel = "fuel" in category_budgets
print(f"Categories budgeted: {count}")
print(f"Food budget: ₦{food_budget:,}")
print(f"Fuel budget set: {has_fuel}")Output: Categories budgeted: 4, then Food budget: ₦6,000, then Fuel budget set: False.
Common mistakes
You look up a key that is not there. Run this:
KeyError: 'fuel'The first lookup printed 3000. The second stopped the program. A KeyError means the dictionary has no such key, and the message names the key Python looked for. Compare it with the keys in your dictionary. If the key might be missing, check with in first, or add it with category_budgets["fuel"] = 5000.
You type a key with different capitals. You write category_budgets["Food"], and the console shows:
KeyError: 'Food'Your dictionary has "food", all in lower case. Python compares keys character by character, so "Food" is not "food". A key must match exactly: the same letters, the same capitals, and no extra spaces. You will meet this one in your own tracker in the steps below.
You ask for a position, as you would with a list. Run this:
KeyError: 0Inside a dictionary's square brackets, Python treats whatever you write as a key. It looked for a key that is the number 0, and found none. That is why this is a KeyError, not the IndexError a list gives. Ask for the value by its key: category_budgets["food"].
You leave out a colon between a key and its value. {"food": 6000, "transport" 4000} gives:
SyntaxError: ':' expected after dictionary keyThis message names the problem. Put a colon between the key and its value. As with every syntax error, nothing in the file runs, not even the lines above it. When the colon is missing after the very first key, Python guesses instead: SyntaxError: invalid syntax. Perhaps you forgot a comma? That guess is wrong here. Look for the missing colon.
Try it yourself
You will give each spending category a budget of its own, and add two lines about them to your report.
-
Run the starting code below. Confirm your report has one
Budgetline and nothing about categories. -
Under your
savings_goal = 50000line, add this line:category_budgets = {"food": 6000, "transport": 4000, "data": 3000, "other": 2000}Run it. Confirm the report has not changed: storing a dictionary prints nothing. You can change the amounts to suit your month. Keep the four keys exactly as written, because later lessons look them up by name.
-
Under your
print_line("Budget", budget)line, add this line:print(f"Categories budgeted: {len(category_budgets)}")A short call like
len(...)can sit inside the braces, as it does here. Run it. Confirm a new line underBudgetsaysCategories budgeted: 4. -
Under that line, add this line:
print_line("Food budget", category_budgets["food"])Run it. Confirm the next line shows your food budget. With the amounts given, that is
Food budget: ₦6,000. -
Under your
Food budgetline, addprint("fuel" in category_budgets). Run it. ConfirmFalseappears under yourFood budgetline. Your dictionary has no"fuel"key. -
Change
"fuel"to"transport". Run it. Confirm the line now saysTrue. Then delete that whole line and run it again. Confirm yourStatusline followsFood budgetonce more. -
Break it on purpose: in your
Food budgetline, change"food"to"Food". Run it. Confirm the report stops afterCategories budgeted, and the console showsKeyError: 'Food', pointing at yourFood budgetline. -
Fix it: change
"Food"back to"food". Run it. Confirm yourFood budgetline returns, with the rest of your report under it.
Your tracker now holds a budget for each category and finds one by its name. Your expenses are still bare numbers, though, with no category attached. The next lesson turns each expense into a dictionary of its own, with a name, a category and an amount.