Drill

ProblemsPython › data

Totals per category

mediumdataPython

A ledger groups every sale under its category so each bucket shows a single sum.

sum_per_category(sales: list<Sale>) → map<string, int>

Solve it in the editor →

Where you start

def sum_per_category(sales: list[Sale]) -> dict[str, int]:
    

Worked examples

CallResult
sum_per_category([Sale(category="food", amount=10), Sale(category="food", amount=15)]){"food": 25}
sum_per_category([Sale(category="a", amount=3), Sale(category="b", amount=4), Sale(category="a", amount=5)]){"a": 8, "b": 4}
sum_per_category([Sale(category="x", amount=1)]){"x": 1}
sum_per_category([Sale(category="p", amount=0), Sale(category="q", amount=-2)]){"p": 0, "q": -2}

Hint

Aggregate into a map keyed by category, adding each amount as you go.

Reference solution in Python
def sum_per_category(sales: list[Sale]) -> dict[str, int]:
    result = {}
    for s in sales:
        result[s.category] = result.get(s.category, 0) + s.amount
    return result

The same problem in another language

More data problems in Python