Crunching CSV Data
Lesson 3 of 5 · View course roadmap
Learn the idea
CSV (comma-separated values) is the universal data format — every spreadsheet exports it. Python's csv module handles the tricky parts (quoted fields, commas inside values):
csv.reader(f)— rows as listscsv.DictReader(f)— rows as dicts keyed by the header row ← usually what you wantcsv.DictWriter(f, fieldnames=[...])— write dicts back out
The analysis pattern: read rows → convert types (CSV gives you strings, even for numbers!) → filter → aggregate. Forgetting int(row["price"]) is the #1 CSV bug.
Where you'll use this
Every ERP, bank, ad platform and spreadsheet exports CSV — it's the lingua franca between systems that don't share an API. This read → convert → aggregate pattern is the seed of every data pipeline (pandas industrialises exactly it).
Common mistakes
- The #1 CSV bug: forgetting values are strings —
"5" * "2"errors and"10" < "9"is True. Convert types immediately. - Naive parsing with .split(",") — real CSVs contain quoted fields with commas inside; the csv module exists because of them.
- Writing CSVs without
newline=""in open() on Windows — you get blank rows between every record.
Pro tip
When a CSV outgrows the csv module (millions of rows, joins, pivots), the upgrade path is pandas: pd.read_csv(f) gives you a DataFrame — and your DictReader mental model transfers directly.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
Parse the CSV in the starter with DictReader and print: the number of orders, the total revenue (qty × price summed), and the name of the product with the biggest single order value (qty × price).
3 3200 laptop
Revenue per row: int(row["qty"]) * int(row["price"]). Use max(rows, key=...) for the biggest.
import csv, io raw = """product,qty,price laptop,2,800 phone,5,300 cable,20,5""" rows = list(csv.DictReader(io.StringIO(raw))) print(len(rows)) print(sum(int(r["qty"]) * int(r["price"]) for r in rows)) biggest = max(rows, key=lambda r: int(r["qty"]) * int(r["price"])) print(biggest["product"])
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.