pythonintermediate10 minutes

Build a Python Expense Tracker with Categorization and Summaries

Create a Python mini-project to manage daily expenses, categorize them, and generate summary reports for monthly spending by category.

Challenge prompt

You need to build a simple expense tracker program in Python. Your program will allow adding daily expenses with an amount, a category (like Food, Transport, Utilities), and a date. It should store the expenses in an appropriate data structure. The program should then be able to generate a summary report that totals spending by category for a given month and year. Implement the following functions: 1. add_expense(amount, category, date) - Adds an expense to the tracker. 2. monthly_summary(year, month) - Returns a dictionary with categories as keys and total spendings as values for the specified month. Make sure your program can handle multiple expenses in the same category and different categories per month.

Guidance

  • Use a list to store expense entries as dictionaries or named tuples with fields for amount, category, and date.
  • Parse and manipulate dates using the datetime module to filter expenses by month and year.
  • Aggregate expenses by category using a dictionary within the summary function.

Hints

  • To filter expenses by month and year, consider extracting year and month from the date object.
  • Initialize your summary dictionary with zero values for unseen categories or use defaultdict from collections.
  • Remember to convert input strings to appropriate types when adding expenses, if you extend the project.

Starter code

from datetime import datetime

expenses = []

def add_expense(amount, category, date):
    """Add an expense: amount as float, category as string, date as datetime.date."""
    expenses.append({'amount': amount, 'category': category, 'date': date})


def monthly_summary(year, month):
    """Return a dict of total expenses by category for given year and month."""
    summary = {}
    # Your code here
    return summary

Expected output

{'Food': 150.0, 'Transport': 75.5, 'Utilities': 100.0}

Core concepts

listsdictionariesdatetime handlingaggregation

Challenge a Friend

Send this duel to someone else and see if they can solve it.