Teach Python CSV Parsing Online With a Tiny DictReader Exercise

Use three fictional rows to teach Python CSV parsing, quoted commas, blank cells, header names, and explicit number conversion in an online lesson.

Author profile photo

By

Share this article:TwitterLinkedIn

Instructor and learner arranging blank cards into rows beside their laptops

A learner splits a CSV row at every comma and gets an unexpected extra column. The name Rivera, Sam has become two fields. That small failure makes a useful starting point for an online Python lesson because students can inspect every character involved.

This 25-minute exercise uses three fictional study records. Give learners five minutes to predict the parsed values, eight to run and explain the example, seven to change one input, and five to report what they learned. Learners need basic Python lists, dictionaries, loops, and function calls. The script uses Python’s standard library and runs in a local interpreter or a browser editor that supports Python.

Predict the fields before running the parser

Put the CSV below beside the code. All names, topics, times, and notes are invented for this exercise.

name,topic,minutes,notes
"Rivera, Sam",loops,25,needs a second example
Ari,functions,20,
Jo,lists,30,"review indexing, then slicing"

Ask students how many data records there are, what the first name should contain, and what value they expect for Ari’s notes. The expected answers are three records, the single string Rivera, Sam, and an empty string for the blank notes cell.

Then inspect the first data row. A plain split(",") produces five fragments because it treats the comma inside the quoted name as a separator too. Have a learner point to the quotes around the name and explain what should stay together. The final row gives a second example of the same issue inside notes.

Hands arranging blank cards in rows, with a wide card kept together inside a blue frame

Read the rows by their header names

Copy this complete script into a Python file or editor and run it. StringIO supplies a text stream from the small example, so everyone starts with the same input.

import csv
from io import StringIO

sample = """name,topic,minutes,notes
"Rivera, Sam",loops,25,needs a second example
Ari,functions,20,
Jo,lists,30,"review indexing, then slicing"
"""

reader = csv.DictReader(StringIO(sample, newline=""))
rows = list(reader)

print(reader.fieldnames)
print(len(rows))
print(repr(rows[0]["name"]))
print(repr(rows[1]["notes"]))
print(sum(int(row["minutes"]) for row in rows))

The output should be:

['name', 'topic', 'minutes', 'notes']
3
'Rivera, Sam'
''
75

With these defaults, DictReader takes its keys from the first row. It consumes that header separately from the three data records. The quoted commas stay inside their fields, while minutes arrives as text. The script explicitly calls int() before adding the values. repr() makes the empty string visible in the output. Python CSV documentation

Ask the driver to read rows[0]["name"] aloud as “the name field in the first data record.” Then have the observer identify the corresponding raw text. That short explanation helps you check whether the learner understands the header mapping.

Change one input and explain the result

Have each pair choose one change, predict its effect, run the script, and compare the result with the prediction.

  • Remove the comma from the first name. The parser still returns three records and four header names. The name value changes, while the total remains 75.
  • Change 25 to 40. The total becomes 90. Ask where text becomes a number in the code.
  • Replace 25 with a blank cell. Parsing still produces a record, but int("") raises ValueError. Ask the learner to identify the blank field and decide what the input requirements should be before changing the calculation.
  • Rename the header from minutes to duration. The dictionary key changes. The unchanged calculation raises KeyError when it asks for "minutes". Ask the learner to compare the printed headers with the key used in the code.

For the blank-time variation, a reasonable next step is to require a whole-number duration and report which record needs correction. A blank value could also mean that the duration is unknown. Have students state the rule they intend before assigning a replacement value.

Learner comparing three paper rows with a checklist and pointing to an empty square

Move from the shared example to a file

Once the example is understood, save just the CSV block as a UTF-8 file named practice.csv. Replace the stream-and-read section with the following code, keeping import csv and the later output statements.

with open("practice.csv", encoding="utf-8", newline="") as source:
    reader = csv.DictReader(source)
    rows = list(reader)

Run the script from the folder containing the CSV file. The output should match the original. Opening with newline="" lets the CSV module handle newline conventions. If the editor cannot access local files, learners can continue using the original stream example. Python CSV file examples

Finish with a short parser check

Ask each learner to add a fourth invented record with a comma inside one quoted field, then explain its parsed name, notes, and minutes. Check the new record count and total against their prediction. End with one sentence explaining why splitting at every comma failed on the original input.

Pairs can swap the driver and observer roles before the final change. A partner should be able to rerun the example and explain the result using the same input. Online pair programming guide

If the cohort uses a browser editor, test its editor, execution, and preview hostnames before a Focus Room session. Add the required hosts to the room’s allowlist, then review the code and output in the teaching tools you use with learners. Hostname rules apply in the participating browser during the active extension session. Focus Room website-rule setup

    Teach Python CSV Parsing Online With a Tiny DictReader Exercise | Focus Room Blog