Totals from a CSV export
Task
csv_text is a CSV file with the header customer,note,amount. Notes can contain commas inside quotes, and some rows have an empty amount. Write total_by_customer(csv_text) that returns {customer: total amount}, skipping rows with no amount, with totals rounded to 2 decimal places.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
total_by_customer('customer,note,amount\nAcme,"paid, late",12.50\nBolt,,5\nAcme,ok,7.25\n') | {'Acme': 19.75, 'Bolt': 5.0} |
total_by_customer('customer,note,amount\nAcme,"refund pending, check",\nBolt,a,0.1\nBolt,b,0.2\n') | {'Bolt': 0.3} |
total_by_customer('customer,note,amount\n') | {} |
- Splitting lines on commas breaks on quoted notes such as
"paid, late". Thecsvmodule handles quoting. csv.DictReader(io.StringIO(text))gives one dict per row, keyed by the header.
Show solution
import csv
import io
def total_by_customer(csv_text):
totals = {}
for row in csv.DictReader(io.StringIO(csv_text)):
amount = (row['amount'] or '').strip()
if not amount:
continue
totals[row['customer']] = round(totals.get(row['customer'], 0) + float(amount), 2)
return totalsNever parse CSV with split(","): quoting, embedded commas and newlines need a real parser. For money in production use decimal.Decimal; rounding floats is acceptable for a report like this one.
Why this works
Never parse CSV with split(","): quoting, embedded commas and newlines need a real parser. For money in production use decimal.Decimal; rounding floats is acceptable for a report like this one.
Revise in the Python for Data Engineers guide, or test yourself with the Python practice sets.