Python
DictReader and DictWriter
Learn CSV as dicts with DictReader and DictWriter.
Reading dictionaries with DictReader
csv.DictReader(f) returns each row as a dictionary. The header row in the file becomes the keys; data rows fill in the values. You access with a key like row["name"] and don't have to remember column order.
This method is very readable for data where header names are meaningful in code. For instance member["email"] is clearer than row[3]. The dict structure also means adding or removing a column barely affects the code.
Writing dictionaries with DictWriter
You create a writer with csv.DictWriter(f, fieldnames=["name", "age"]). writer.writeheader() writes the header row; writer.writerow({"name": "Ayşe", "age": 30}) builds a data row from a dict.
The fieldnames list fixes the column order; even if the dict's keys are in a different order, the output stays consistent. This is handy when you collect data from a user and need a stable column order.
Exercise Read the name column with DictReader
Start with import csv. In a with open("people.csv", "w", encoding="utf-8", newline="") as f: block write three lines with f.write("name,age\n"), f.write("Ayşe,30\n") and f.write("Ali,25\n"). Then in a with open("people.csv", "r", encoding="utf-8", newline="") as f: block do reader = csv.DictReader(f) and rows = list(reader). Print the name from the second row with print(rows[1]["name"]).
Show example solution
import csv
# Write header + two rows to a CSV file
with open("people.csv", "w", encoding="utf-8", newline="") as f:
f.write("name,age\n")
f.write("Ayşe,30\n")
f.write("Ali,25\n")
# Read with DictReader and print the name from the second row
with open("people.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
rows = list(reader)
print(rows[1]["name"])
Test yourself
-
Match the DictReader parts
- DictReader
- Reads as dictionaries
- row
- Dictionary row
- header
- Key row
- key
- Dictionary key
-
What does DictReader yield per row?
- A string
- A dictionary
- A list
- A tuple
Show answer
A dictionary — DictReader returns each row as a dictionary; keys come from the header.
-
Complete the DictWriter fieldnames
writer = csv.DictWriter(f, ____=["name", "age"])
Show answer
writer = csv.DictWriter(f, fieldnames=["name", "age"])
Next lesson: json.load and dump