← All Exercises

Aggregate CSV Rows by Category

basicpython~20min

Background

csv.DictReader maps each row to a dictionary and handles quoting rules that naive split(',') cannot, which matters for real exports.

Problem

Read CSV text with category and amount columns, ignore blank rows, sum amounts per category, reject non-numeric or negative amounts with the offending line number, and return (category, total) pairs sorted by total descending then category ascending.

Input

CSV text whose header includes category and amount.

Output

A list of (category, total) tuples sorted by total descending, then category ascending.

Sample tests

Sample 1

Input: category,amount
books,10
food,5
books,2.5
food,7
Expected: [('books', 12.5), ('food', 12.0)]

Sample 2

Input: category,amount
 tools , 3 

 tools, 1
Expected: [('tools', 4.0)]

Sample 3

Input: category,amount
books,-2
Expected: ValueError: line 2: amount must be non-negative

Your solution

Learning objective

Aggregate tabular text safely with csv.DictReader and produce deterministic sorted totals.