Spending by Category

Python for AIHard+10 XP+10

Spending by Category

A bank app stores your payments as a list of dictionaries. Each payment has a "category" and an "amount".

Write category_totals(payments) that returns a dictionary of each category to the total amount spent in it.

  • A category appears in the result only if it has at least one payment.
  • An empty list gives an empty dictionary.

Examples

payments = [{'category': 'food', 'amount': 12}, {'category': 'bus', 'amount': 3}, {'category': 'food', 'amount': 8}]
returns {'food': 20, 'bus': 3}
payments = [{"category": "rent", "amount": 500}, {"category": "food", "amount": 40}, {"category": "food", "amount": 25}, {"category": "fun", "amount": 15}]
returns {'rent': 500, 'food': 65, 'fun': 15}
payments = []
returns {}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run