pythonintermediate10 minutes

Build a Expense Tracker with Category Summaries

Create a Python function that manages a list of expenses and produces a summary by category, enabling users to track their spending habits effectively.

Challenge prompt

Write a function `expense_summary` that takes a list of expenses, where each expense is represented as a dictionary with keys `amount` (a float) and `category` (a string). Your function should return a dictionary that summarizes the total spending per category. Additionally, include a key 'total' in the output dictionary representing the total amount spent across all categories. For example, given the input: [{'amount': 15.50, 'category': 'food'}, {'amount': 20.00, 'category': 'transport'}, {'amount': 5.00, 'category': 'food'}] your function should return: {'food': 20.50, 'transport': 20.00, 'total': 40.50} Make sure your code is efficient and handles the case when the input list is empty.

Guidance

  • Loop through each expense to aggregate amounts by category using a dictionary.
  • Keep a running total of all expenses to include in the result under the 'total' key.
  • Consider edge cases like empty input lists and ensure your function returns an empty summary with a total of 0.

Hints

  • Use the dict.get() method to simplify adding amounts to categories in the summary.
  • Initialize the total spending variable outside the loop and update it for each expense.
  • To handle empty input, the default output should be {'total': 0} with no category keys.

Starter code

def expense_summary(expenses):
    # Implement your solution here
    pass

Expected output

{'food': 20.50, 'transport': 20.00, 'total': 40.50}

Core concepts

dictionarieslist iterationaggregationhandling edge cases

Challenge a Friend

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