Your expense listing shows amounts with no names. Nothing in your report says which ₦2,500 was lunch. This lesson turns each expense into a dictionary with a name, a category and an amount.
The concept
Here is your tracker as the last lesson left it. Run it:
Your listing shows five amounts, and nothing about what they paid for. Now run this:
Each line has a name and an amount. Look at the list. Its items are not numbers. Each item is a dictionary, and every one has the same three keys: "item", "category" and "amount".
A dictionary that describes one thing, with the same keys as the others in its list, is a record. Each key and its value make one field of the record.
The loop works as it did with numbers. On each pass, record holds one whole dictionary. record["item"] reads its item field, and record["amount"] reads its amount. That is the same lookup as category_budgets["food"], done once per record.
Records come with one catch. sum, max and min work on plain numbers, and a record is a whole dictionary. So you build a plain list of numbers from the records. Run this:
amounts = [] makes an empty list. The loop runs once per record, and each pass appends that record's amount to the end of amounts. After the loop, amounts holds [1500, 2500, 800]. Those are plain numbers, in the same order as the records, so sum can add them up.
The syntax
expenses = [
{"item": "Bus fare", "category": "transport", "amount": 1500},
{"item": "Lunch", "category": "food", "amount": 2500},
]
expenses.append({"item": "Suya", "category": "food", "amount": 800})- The square brackets hold the list. Each pair of curly braces holds one record.
- A comma goes after each record. Python accepts one after the last record too, so adding a record later means adding one line.
- The list can spread over several lines. Python keeps reading until it reaches the closing
]. - Give every record the same keys, spelled the same way. A loop reads the same field from every record.
appendadds a whole record to the end of the list, the same way it added a number.
Reading a field inside a loop:
for record in expenses:
amount = record["amount"]On each pass, the loop variable holds one record. Square brackets with a key in quotes read one field, as with any dictionary.
Building a plain list from records:
amounts = []
for record in expenses:
amounts.append(record["amount"])[]is an empty list. It goes above the loop, so it is created once, likefound = 0in yourcount_overfunction.- Each pass appends one record's amount.
- After the loop,
amountshas one number per record, in the same order. Hand that list tosum,max,minorcount_over.
A minimal working example
def print_line(label, amount):
print(f"{label}: ₦{amount:,}")
expenses = [
{"item": "Bus fare", "category": "transport", "amount": 1500},
{"item": "Lunch", "category": "food", "amount": 2500},
{"item": "Suya", "category": "food", "amount": 800},
]
amounts = []
for record in expenses:
amounts.append(record["amount"])
total = sum(amounts)
for record in expenses:
print_line(" " + record["item"], record["amount"])
print_line("Total spent", total)Output: Bus fare: ₦1,500, Lunch: ₦2,500 and Suya: ₦800, each indented by two spaces, then Total spent: ₦4,800. The + joins two strings end to end, so " " + record["item"] puts two spaces in front of each name. The category field is not used yet. The next lesson puts it to work.
Common mistakes
You hand the records straight to sum. Run this:
TypeError: unsupported operand type(s) for +: 'int' and 'dict'dict is Python's short name for a dictionary. sum starts from 0 and adds each item to it. The first item here is a whole dictionary, and Python cannot add a dictionary to a number. The 'int' in the message is that starting 0. max and min also stop with a TypeError that mentions 'dict'. Build a list of amounts first, and hand that list to sum.
You leave the quotes off a key. Run this:
NameError: name 'amount' is not defined. Did you mean: 'amounts'?Without quotes, Python reads amount as the name of a variable, and your program has no variable by that name. Ignore the suggestion: it is a spelling guess, and amounts is your list, not a key. A key is text, so it needs quotes: record["amount"].
You read a field with a dot. You write record.amount, and the console shows:
AttributeError: 'dict' object has no attribute 'amount'A dot after a value reaches its methods, like .append on a list. Python calls a name after a dot an attribute. A dictionary keeps its fields as keys, not attributes, so it has no amount attribute. Use square brackets: record["amount"].
One record spells a key differently. Run this:
KeyError: 'amount'The first record printed, then the program stopped on the second. The key in the message is spelled correctly, so the lookup is fine. The fault is in the data: the Lunch record says "amout". When a KeyError names the right key, check the spelling in each record. When it names a misspelled key, fix the lookup instead.
Try it yourself
You will turn your expenses into records, list them by name, and keep every number in your report the same.
-
Run the starting code below. Confirm each expense in your listing is an amount with no name.
-
Under your
fuel = int(fuel_receipt)line, add your records. Then add a loop that builds a list of their amounts:expenses = [ {"item": "Bus fare", "category": "transport", "amount": 1500}, {"item": "Lunch", "category": "food", "amount": 2500}, {"item": "Data bundle", "category": "data", "amount": 3500}, {"item": "Suya", "category": "food", "amount": 800}, ] expenses.append({"item": "Fuel", "category": "transport", "amount": fuel}) amounts = [] for record in expenses: amounts.append(record["amount"])If you changed your amounts, use your own here, in the same order. Keep each category to one of the keys in your
category_budgets, because the next lesson matches them up.Run it. Confirm your report has not changed. Your old list of numbers comes straight after this code, and it takes the name
expensesback. A name holds one value at a time. Nothing readsamountsyet. -
Point your totals at the new list. Change
expensestoamountsin five lines, so this part of your code reads:total = sum(amounts) biggest = max(amounts) smallest = min(amounts) left = budget - total mid_spends = count_over(amounts, 1000) large_spends = count_over(amounts, 3000)left = budget - totaldoes not change. Leavecount = len(expenses)as it is too. After the next step, it counts your records, one per expense. Run it. Confirm every number in your report is the same as in step 1. If one changed, an amount in your records differs from your old list. -
Retire your old list. Your listing still reads it, while your totals now read your records. Change one copy of an amount and forget the other, and the two disagree. Delete the two lines that build the old list:
expenses = [1500, 2500, 3500, 800], with your own amounts if you changed them, andexpenses.append(fuel). Keep the line that appends your Fuel record.With the old list gone,
expensesholds your records everywhere below them. So your listing loop must read records too. Replace it, theforline and theprintunder it, with:for record in expenses: print_line(" " + record["item"], record["amount"])Run it. Confirm each expense in your listing now starts with its name. With the names given, the first is
Bus fare: ₦1,500. Every line below the listing should be unchanged. If aTypeErrorappears instead, look at the line the traceback points at. One of the five lines from step 3 may still sayexpenses. -
Break it on purpose: change
total = sum(amounts)tototal = sum(expenses). Run it. Confirm none of your report prints, and the console shows aTypeErrorthat mentions'int' and 'dict', pointing at yourtotalline. -
Fix it: change
expensesback toamounts. Run it. Confirm your report returns, with every expense listed by name. Each amount now lives in one place, its record.
Your expenses are records now, each with a name, a category and an amount. Your report uses the names, but the categories sit unused. The next lesson adds up your spending per category and checks each total against its budget.