Skip to main content

Programming fundamentals · Beginner · 18 min

Store each expense in a list and print a spending summary

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim

You will change the budget tracker so it keeps every expense as a dictionary in a list, then prints a summary table with each expense, the biggest one and a total per category after you type done.

On this page

At the end of part 4 your tracker could take any number of expenses, but it only remembered two things about them: how much they added up to and how many there were. Ask it "what did I spend the most on?" or "how much went on food?" and it has no idea, because each amount was added to the total and then forgotten.

In this part the tracker stops forgetting. You keep every expense, with its name, its category and its amount, and after you type done the program prints a summary like this:

Text
Spending summary
--------------------------------
Bus fare      travel       1,500
Lunch         food         2,500
Rent          housing     20,000
--------------------------------
3 expenses, spent 24,000
Biggest: Rent (20,000)

To get there you need two new kinds of value that work together. A list holds many values in order. A dictionary holds one thing described by named fields. The tracker uses a list of dictionaries: one dictionary per expense, all kept in one list.

Step 1 · Open the tracker where part 4 left it

Move into the folder you have used since part 1:

Bash
mkdir -p ~/budget-tracker
cd ~/budget-tracker

Your budget.py should be the file part 4 ended with: it asks for a monthly budget, asks for expenses until you type done (in any capitals), prints a running total after each one, then the count, the total and a balance message from part 3. The block below is that file, exactly as part 4 left it. If you are starting here, or your file has drifted, replace yours with it so the rest of the steps line up with your screen. On Windows, open budget.py in your editor and type the lines between the two PY markers.

Bash
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = 0
count = 0

while True:
    answer = input("Expense (or done): ").strip().lower()
    if answer == "done":
        break
    spent += int(answer)
    count += 1
    print(f"Running total: {spent}")

balance = budget - spent
low_mark = budget // 10
print(f"Expenses entered: {count}, total {spent}.")

if balance < 0:
    print(f"Warning: you are {-balance} over budget.")
elif balance < low_mark:
    print(f"Careful: only {balance} left, less than 10% of your budget.")
else:
    print(f"Balance: {balance} left of {budget}.")
PY

Typing the same answers every time you test gets slow. printf '%s\n' prints each word you give it on its own line, and the | (pipe) sends those lines to the program as if you had typed them. Here the answers are a budget of 50000, two expenses and done:

Bash
printf '%s\n' 50000 20000 1500 done | python3 budget.py

The questions still print, but your answers do not appear on screen, so the prompts run together on one line. That is normal when input comes from a pipe. You can still run python3 budget.py and type the answers yourself whenever you prefer.

Check it worked

After the run-together prompts you see Running total: 20000 and Running total: 21500, then Expenses entered: 2, total 21500. and, on the last line, Balance: 28500 left of 50000. If your output differs, replace budget.py with the block above and run the command again.

Step 2 · Keep several values in one list

Try lists in a scratch file first, so budget.py stays as it is:

Bash
cat > lists_demo.py <<'PY'
amounts = [1500, 2500, 20000]
print(amounts)
print(len(amounts))
print(amounts[0])

amounts.append(3000)
print(amounts)

for amount in amounts:
    print(f"Paid {amount}")
PY
python3 lists_demo.py

Line by line:

  • amounts = [1500, 2500, 20000] makes a list. Square brackets hold the values, separated by commas, and the list keeps them in the order you wrote them. One variable now refers to three numbers.
  • len(amounts) gives the number of items in the list: 3.
  • amounts[0] reads one item by its position, called its index. Python counts from 0, so [0] is the first item and [2] is the third. Asking for amounts[5] stops the program with IndexError: list index out of range, because there is no sixth item.
  • amounts.append(3000) adds 3000 to the end of the list. The dot means "use something that belongs to this value": append is a method, a function that lists carry around with them. The list grows to four items.
  • for amount in amounts: is a for loop. It runs the indented line once for each item in the list, and each time amount refers to the next item. You do not count anything or say when to stop; the loop ends when the list runs out.

A while loop, from part 4, repeats until something tells it to stop. A for loop repeats once per item in a collection. The tracker uses both: while to keep asking, for to go through what was collected.

Check it worked

The output is:

Text
[1500, 2500, 20000]
3
1500
[1500, 2500, 20000, 3000]
Paid 1500
Paid 2500
Paid 20000
Paid 3000

There are four Paid lines, one per item, because the list had four items when the loop ran.

Step 3 · Describe one expense with a dictionary

A list of bare amounts loses what each amount was for. A dictionary stores one thing as a set of labelled fields. Each field is a key (the label) and a value. Make a second scratch file:

Bash
cat > dict_demo.py <<'PY'
expense = {"item": "Bus fare", "category": "travel", "amount": 1500}
print(expense)
print(expense["item"])
print(expense["amount"] * 2)

expense["amount"] = 1800
print(expense)
print("category" in expense)
PY
python3 dict_demo.py

Line by line:

  • {"item": "Bus fare", "category": "travel", "amount": 1500} makes a dictionary with three keys. Curly braces hold the fields, a colon joins each key to its value, and commas separate the fields. The keys here are strings; the values can be anything, text or numbers.
  • expense["item"] looks up a value by its key. It uses square brackets like a list, but with a key instead of a position. You never need to remember that the amount is "the third field"; you ask for "amount" by name.
  • expense["amount"] * 2 shows that the value you get back is a real number you can do arithmetic with.
  • expense["amount"] = 1800 replaces the value stored under a key that already exists. Assigning to a key that does not exist yet adds a new field instead. You use both in the last step.
  • "category" in expense asks whether the dictionary has that key, and gives True or False.

Ask for a key that is not there, such as expense["price"], and Python stops with KeyError: 'price'. Like NameError in part 1, it nearly always means a typo or a key spelled with different capitals: "Amount" and "amount" are different keys.

Check it worked

The output is:

Text
{'item': 'Bus fare', 'category': 'travel', 'amount': 1500}
Bus fare
3000
{'item': 'Bus fare', 'category': 'travel', 'amount': 1800}
True

Python prints dictionaries with single quotes even though you typed double quotes. Both mean the same thing. The amount changed to 1800 in the fourth line and nothing else moved.

You are done with the scratch files:

Bash
rm lists_demo.py dict_demo.py

Step 4 · Save every expense the user types

Now combine the two. Each time round the while loop, the tracker asks for the item, its category and its amount, packs them into a dictionary and appends that dictionary to a list called expenses. Replace budget.py:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 5)
currency = "NGN"
budget = int(input("Monthly budget: "))

expenses = []
spent = 0

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ")
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)
    spent += amount

print()
print(f"You entered {len(expenses)} expenses")
print(expenses)

left = budget - spent
print(f"Spent {spent}, left {left}")

if left < 0:
    print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
    print(f"Careful: only {currency} {left:,} left")
else:
    print(f"You have {currency} {left:,} left this month.")
PY
printf '%s\n' 50000 'Bus fare' travel 1500 Rent housing 20000 done | python3 budget.py

What changed:

  • expenses = [] makes an empty list before the loop. It has to exist before the first append, and it has to be outside the loop: inside, it would be emptied again every time round.
  • The first question is now the item name, and typing done there still ends the loop with break, as in part 4. item.strip().lower() == "done" tidies a copy of the answer only for the comparison, so Done or DONE ` still ends the loop, while `item itself keeps the capitals you typed (Bus fare stays Bus fare in the summary).
  • count has gone: len(expenses) gives the same number, because there is one dictionary in the list per expense. spent += amount is the same running total as part 4, now added from amount instead of int(answer). The Running total line has gone too, because the summary in the next step shows every amount.
  • currency = "NGN" and the :, in {left:,} come back from part 1: the currency code you chose then, and the comma format that groups thousands so 28500 prints as 28,500. The balance messages now use them so they read like money. balance is renamed left, as it was in part 1, and budget / 10 does the same job as part 4's low_mark. A single / can give a number with a decimal point (50000 / 10 is 5000.0), which is fine here because it is only compared, never printed. Put your own currency code on that line if it is not NGN.
  • expense = {...} builds a new dictionary from the three answers. The keys are fixed text in quotes; the values are the variables item, category and amount, so each expense gets the answers you just typed.
  • expenses.append(expense) adds that dictionary to the end of the list.
  • print() with nothing inside prints an empty line. It ends the line of run-together prompts, so the results start on a fresh line.
  • print(expenses) shows the raw list. It is not pretty, but it proves every expense was kept. You replace it with a proper table in the next step.

In the printf line, 'Bus fare' is in quotes because it contains a space. Without them, Bus and fare would be sent as two separate answers.

Check it worked

After the prompts you see:

Text
You entered 2 expenses
[{'item': 'Bus fare', 'category': 'travel', 'amount': 1500}, {'item': 'Rent', 'category': 'housing', 'amount': 20000}]
Spent 21500, left 28500
You have NGN 28,500 left this month.

The square brackets around the whole line mark the list; each pair of curly braces inside is one expense, in the order you typed them.

Step 5 · Print each expense as a line and add up the total

With every expense in a list, you no longer need a running total inside the while loop. A for loop over the list can print each expense and add up the amounts at the same time. Replace budget.py:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 5)
currency = "NGN"
budget = int(input("Monthly budget: "))

expenses = []

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ")
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

left = budget - spent
print()
if left < 0:
    print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
    print(f"Careful: only {currency} {left:,} left")
else:
    print(f"You have {currency} {left:,} left this month.")
PY
printf '%s\n' 50000 'Bus fare' travel 1500 Lunch food 2500 Rent housing 20000 done | python3 budget.py

The new lines:

  • "-" * 32 repeats the string - 32 times, which draws a line as wide as the table.
  • for expense in expenses: takes each dictionary from the list in turn. Inside the loop, expense is one expense, so expense["amount"] is that expense's amount.
  • Inside the f-string, expense['item'] uses single quotes because the whole f-string is wrapped in double quotes. Mixing them keeps the two kinds of quote easy to tell apart.
  • :<14 after a value means "left-align it in a space 14 characters wide", padding with spaces. :<10 does the same in 10 characters. :>8, right-aligns the amount in 8 characters and groups thousands with commas, so the units of every amount line up in one column, the way a bank statement does.
  • spent = 0 before the loop and spent += expense["amount"] inside it build the total. This is the same += running total as part 4, but now it is worked out from the stored list, so it always matches what the table shows.

An item name longer than 14 characters pushes the rest of its row to the right. Shorten the name, or make the 14 bigger and the 32 bigger by the same amount.

Check it worked

After the prompts you see:

Text
Spending summary
--------------------------------
Bus fare      travel       1,500
Lunch         food         2,500
Rent          housing     20,000
--------------------------------
3 expenses, spent 24,000

You have NGN 26,000 left this month.

The commas in the amounts sit directly above each other. If the columns wander, check that every row uses the same widths and that the code font in your terminal is monospaced (it almost always is).

Step 6 · Find the biggest expense

To find the largest amount, go through the list once and remember the biggest expense seen so far. Every time you meet a bigger one, it takes over. Add this block straight after the line that prints expenses, spent. Here is the full file again so you can replace it in one go:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 5)
currency = "NGN"
budget = int(input("Monthly budget: "))

expenses = []

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ")
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

if len(expenses) > 0:
    biggest = expenses[0]
    for expense in expenses:
        if expense["amount"] > biggest["amount"]:
            biggest = expense
    print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")

left = budget - spent
print()
if left < 0:
    print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
    print(f"Careful: only {currency} {left:,} left")
else:
    print(f"You have {currency} {left:,} left this month.")
PY
printf '%s\n' 50000 'Bus fare' travel 1500 Lunch food 2500 Rent housing 20000 Taxi travel 2000 done | python3 budget.py

How the new block works:

  • if len(expenses) > 0: only runs the search when there is at least one expense. If you type done straight away the list is empty, and expenses[0] would stop the program with IndexError.
  • biggest = expenses[0] starts with the first expense as the best guess.
  • The for loop compares each expense's amount with the current biggest. > is a comparison like the ones in part 3. When it is true, biggest = expense makes this expense the new biggest.
  • After the loop, biggest refers to the dictionary with the largest amount, so you can print its item name as well as its amount.

Notice the indentation: the for loop is inside the if, and the inner if is inside the for. Each extra level of indentation means "this belongs to the line above". The print lines up with for, so it runs once, after the loop, not once per expense.

In this test run Rent is the third expense, not the first, so the loop has to replace its first guess (Bus fare) to find it.

Check it worked

Below the table, after 4 expenses, spent 26,000, there is exactly one line reading Biggest: Rent (20,000). If you see four Biggest lines, the print is indented inside the for loop; move it left by one level.

Step 7 · Total each category in a second dictionary

The last question the summary answers is how much went on each category. You do not know the categories in advance (you type them), so the program builds a dictionary as it goes: each key is a category, each value is the total spent in it.

There is one trap first. If you type Food for one expense and food for another, they are different strings, so they would become two separate categories. .lower() is a string method that returns the text in lower case, which makes Food, FOOD and food all the same. Replace budget.py with the finished version for this part:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 5)
currency = "NGN"
budget = int(input("Monthly budget: "))

expenses = []

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

if len(expenses) > 0:
    biggest = expenses[0]
    for expense in expenses:
        if expense["amount"] > biggest["amount"]:
            biggest = expense
    print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")

totals = {}
for expense in expenses:
    category = expense["category"]
    if category in totals:
        totals[category] = totals[category] + expense["amount"]
    else:
        totals[category] = expense["amount"]

print()
print("By category")
for category, total in totals.items():
    print(f"{category:<24}{total:>8,}")

left = budget - spent
print()
if left < 0:
    print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
    print(f"Careful: only {currency} {left:,} left")
else:
    print(f"You have {currency} {left:,} left this month.")
PY

The new parts:

  • input("Category: ").lower() runs input, then calls .lower() on the text it returns, so category is always lower case before it goes into the dictionary.
  • totals = {} is an empty dictionary, just as [] was an empty list.
  • For each expense, if category in totals: checks whether that category already has a total. If it does, the amount is added to it. If not, the else branch creates the key with this amount as its first value. Without that check, adding to a key that does not exist yet would stop with KeyError.
  • totals.items() gives the key and value of each entry as a pair, and for category, total in ... unpacks each pair into two variables. Dictionaries keep keys in the order they were first added, so categories print in the order you first used them.
  • {category:<24}{total:>8,} uses widths that add up to 32, so the category totals line up under the amounts in the table above.

Category names can be in any language you write in. abinci, chakula or nourriture work exactly like food, as long as you type the same word each time.

Run it with six expenses, two of them typed as Food and food:

Bash
printf '%s\n' 50000 'Bus fare' travel 1500 Lunch Food 2500 Rent housing 20000 'Data bundle' phone 3000 Groceries food 6000 Taxi travel 2000 done | python3 budget.py

Check it worked

The end of the output is:

Text
By category
travel                     3,500
food                       8,500
housing                   20,000
phone                      3,000

You have NGN 15,000 left this month.

There is one food line totalling 8,500 (Lunch plus Groceries), even though you typed Food once. Add the four category totals: they come to 35,000, the same as the spent figure above the table.

Step 8 · Use the tracker for real and try the edge case

Run it the normal way and type your own expenses for a day or a week:

Bash
python3 budget.py

A session looks something like this, with your answers after each colon:

Text
Monthly budget: 50000
Item (or done): Data bundle
Category: phone
Amount: 3000
Item (or done): Lunch
Category: food
Amount: 2500
Item (or done): done

The summary table follows. Now check the edge case: typing done before entering anything.

Bash
printf '%s\n' 50000 done | python3 budget.py

Finally, open PLAN.txt from part 1 in your editor and add (done) to the end of the line that starts 5., "Keep every expense in a list and show a summary".

Check it worked

Your own session ends with a table of the expenses you typed. The empty run prints the headings, 0 expenses, spent 0, no Biggest line, an empty By category section and You have NGN 50,000 left this month., with no error. budget.py is now around fifty lines long, which is exactly what part 6 tidies up.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.