Deviopath › Python

CSV Totals per Category

Hard · Data Processing

The csv module handles the tricky parts of CSV, like quoted fields with commas inside ("Food, takeout"). csv.DictReader reads the header row and gives you every other row as a dict. Money should be added with decimal.Decimal, never with floats.

Write category_totals(csv_text). The text starts with a header row that has (at least) the columns category and amount, in any order. Return a dict with:

- "totals": category (with surrounding spaces removed) mapped to its total amount, as a string rounded to 2 decimals, half up, like "20.00". Use total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP).

- "skipped": how many rows had an empty or non-numeric amount (skip those rows)

Refunds are negative amounts.

Next: Tiny Template Engine