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
- A list of expenses
- A function that totals the cost by type
- A tidy report with a grand total
Steps
- Read the
expenseslist of dictionaries. total_by_typebuilds a new dictionary of totals.- Press Run to see the report.
- 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
- Show the biggest single expense.
- Read the expenses from a file.
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()))