← Data analysis with Python

csv.DictReader and summaries

Read rows as dictionaries and total them up by group.

Start this lesson

csv.DictReader uses the header line for you: each row becomes a dictionary like {"store": "North", "units": "30"}. Code that says row["units"] is easier to read than row[3], and it keeps working if someone adds a column. Combine it with the dictionary-counting pattern and you can answer "how much per group?" questions: total units per store, rainfall per region, and so on.

import csv, io

text = """store,units
North,30
South,22
North,12
"""
totals = {}
for row in csv.DictReader(io.StringIO(text)):
    store = row["store"]
    totals[store] = totals.get(store, 0) + int(row["units"])
print(totals)

For each row, add its units to that store’s running total. The result is {"North": 42, "South": 22}. This "group and total" idea is exactly what pandas groupby will do for us later.

DictReader values are still text. Convert with int() or float() at the moment you use them.