csv.DictReader & in-memory streams
Read a small CSV report
Lesson 18 of 20 · 14 min · Module 6: Reliable inputs & practical reports
CSV is a common way to exchange table-shaped information. A real CSV reader understands quoted fields and column headers.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Read CSV by header names
- Preserve quoted values and skip invalid rows
The idea
csv.DictReader turns each row into a dictionary keyed by the header. Wrap text in io.StringIO to read it in memory; this exercise does not access files on your computer.
import csv, io
rows = csv.DictReader(io.StringIO("name,minutes\nAlex,12\n"))
print(list(rows))
01Let the format reader do its job
A title such as Lists, tuples contains a comma that belongs to one field. Splitting a row on every comma loses that distinction.
02Normalize a row at the boundary
Strip the title and convert minutes before appending a clean dictionary. The rest of the application then sees a consistent shape.
03Decide what rejection means
This exercise skips invalid rows. Other applications might instead collect errors with line numbers. Choose a policy and communicate it.
Your turn
read_sessions(text) for CSV with title and minutes headers. Return dictionaries with a stripped, nonempty title and integer minutes greater than zero. Skip invalid rows, including missing fields and non-integer durations. Preserve valid input order and handle quoted titles containing commas.What the checks look for
- Parses and cleans valid rows
- Understands a quoted comma
- Skips broken, missing, and nonpositive values
- Handles header-only and empty input
Take this with you
Use a parser for a structured format, then validate the parsed values.
Go a little further
Return a separate list of rejected row numbers alongside the clean records.