Back
+15 XP
Concept

CSV Processing with `csv.DictReader`

`csv.DictReader` reads comma-separated spreadsheet data directly into clean Python dictionaries where column headers serve as dictionary keys.

python
import csv, io

csv_data = "name,role\nAlice,Admin\nBob,User\n"
reader = csv.DictReader(io.StringIO(csv_data))
for row in reader:
    print(f"{row['name']}: {row['role']}")

# 18. CSV Processing with `csv.DictReader` `csv.DictReader` reads comma-separated spreadsheet data directly into clean Python dictionaries where column headers serve as dictionary keys: ```python import csv, io csv_data = "name,role\nAlice,Admin\nBob,User\n" reader = csv.DictReader(io.StringIO(csv_data)) for row in reader: print(f"{row['name']}: {row['role']}") ``` If an external team adds a new column to the spreadsheet, code using `row[1]` breaks immediately because index offsets shift. `csv.DictReader` ignores column order and reliably accesses values by column name.

Checkpoint

Why is `csv.DictReader` safer than standard `csv.reader`?

Practice

Given `raw = "id,val\n1,100\n"`, parse it with `csv.DictReader(io.StringIO(raw))` and print the value of `val` from the first row.

Terminal
01
Tap code blocks below to assemble
Available Blocks