codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Live project: Expense tracker

Live project: Expense tracker

Group and total expenses with dictionaries.

Use lists, dictionaries, functions and loops to summarise spending.

What you will build

Steps

  1. Read the expenses list of dictionaries.
  2. total_by_type builds a new dictionary of totals.
  3. Press Run to see the report.
  4. Add your own expenses.

Run it

Press Run to see the project work. Then change the data in the editor and run it again.

Challenge

Example code

expenses = [
    {"item": "Tea", "cost": 20, "type": "food"},
    {"item": "Bus", "cost": 35, "type": "travel"},
    {"item": "Lunch", "cost": 120, "type": "food"},
    {"item": "Book", "cost": 250, "type": "study"},
]

def total_by_type(items):
    totals = {}
    for e in items:
        totals[e["type"]] = totals.get(e["type"], 0) + e["cost"]
    return totals

totals = total_by_type(expenses)
for kind, amount in sorted(totals.items()):
    print(kind.ljust(8), amount)
print("-" * 14)
print("Total".ljust(8), sum(totals.values()))

Run this code in the online editor

← Python databases: MySQL and MongoDB