DictReader and DictWriter
- Python course
- Intermediate
- Lesson 72/116
- 5 min
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.
Practice 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"]).
Starter code
import csv
# Write header + two rows to a CSV file
# Read with DictReader and print the name from the second rowSample 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"])Expected output
Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the DictReader parts
| Term | Meaning |
|---|---|
DictReader |
Reads as dictionaries |
row |
Dictionary row |
header |
Key row |
key |
Dictionary key |
2 What does DictReader yield per row?
- A string
- A dictionary Correct answer
- A list
- A tuple
Explanation: DictReader returns each row as a dictionary; keys come from the header.
3 Complete the DictWriter fieldnames
writer = csv.DictWriter(f, ____=["name", "age"])
writer = csv.DictWriter(f, fieldnames=["name", "age"])
Explanation: fieldnames sets the column names and order.