Sub topic 8
Working with named columns using DictReader and DictWriter
This chapter assumes you know basic Python syntax, dicts, lists and strings, the with statement, and how csv.reader and csv.writer work. You should also know why CSV files are opened with newline="" and an explicit encoding.
Why named columns help
csv.reader gives you each row as a list. You then have to remember that index 0 is the name and index 1 is the quantity. If someone adds a column, your indexes break without any error.
csv.DictReader and csv.DictWriter fix this. They treat each row as a dict whose keys are column names. Your code reads row["qty"] instead of row[1], so it stays correct when the column order changes.
Reading with DictReader
DictReader takes the first row of the file as the header. Each later row becomes a dict that maps header names to values.
Suppose items.csv contains this:
name,qty
apple,3
"pear, green",5This code reads it:
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["qty"]) * 2)Every value is a string. The code calls int() on qty before doing arithmetic. Without that call, "3" * 2 would give "33" and no error. The next chapter covers type conversion in detail.
You can read the header names from the fieldnames attribute:
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
print(reader.fieldnames) # ['name', 'qty']
first = next(reader)
print(first)In Python 3.8 and later, each row is a regular dict. Earlier versions returned an OrderedDict.
Writing with DictWriter
DictWriter needs the column names up front, through the fieldnames argument. This argument sets both which keys are written and in what order. It does not write the header row on its own. You call writeheader() for that.
import csv
items = [
{"name": "apple", "qty": 3},
{"name": "pear, green", "qty": 5},
]
with open("items_out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "qty"])
writer.writeheader()
writer.writerows(items)The writer converts non-string values with str(), so the integers are fine here. It also quotes "pear, green" automatically because the value contains a comma.
The flow of data
Common errors
Rows with the wrong number of fields
DictReader handles short and long rows quietly, and the result can surprise you.
| Row problem | What DictReader does |
|---|---|
| Fewer values than headers | Fills the missing keys with `restval`, which is `None` by default |
| More values than headers | Puts the extra values in a list under the key `restkey`, which is `None` by default |
You can change both defaults when you create the reader, for example csv.DictReader(f, restval="", restkey="extra"). Check for None values if your input comes from people or from other systems.
Keys that DictWriter does not expect
If a dict contains a key that is not in fieldnames, DictWriter raises ValueError. To drop the extra keys, pass extrasaction="ignore":
import csv
row = {"name": "plum", "qty": 2, "color": "purple"}
with open("plums.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "qty"], extrasaction="ignore")
writer.writeheader()
writer.writerow(row)A dict that is missing a key does not raise an error. The writer fills the gap with restval, which is an empty string by default.
Files with no header row
DictReader always treats the first line as the header. If your file has no header, the first data row becomes the keys and you lose that row. Pass the names yourself with fieldnames:
import csv
with open("no_header.csv", "w", newline="", encoding="utf-8") as f:
f.write("apple,3\npear,5\n")
with open("no_header.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f, fieldnames=["name", "qty"]):
print(row)When you give fieldnames, DictReader reads every line as data.
Duplicate and padded headers
If two columns share a name, the later value overwrites the earlier one in each dict. If a header has stray spaces, such as " qty", then row["qty"] raises KeyError. Print reader.fieldnames when a lookup fails. You can also clean the names yourself by passing fieldnames=[h.strip() for h in header] after reading the header line.
Exercise
Exercise
A file people.csv has the header name,age,city. You read it with csv.DictReader and compute row["age"] + 1 for the first row, and Python raises a TypeError. What is the cause, and what is the fix?
Show answer
Every value from a CSV reader is a string, so row["age"] is something like "30" and adding the integer 1 to a string fails. Convert it first with int(row["age"]) + 1.
Exercise
You call csv.DictWriter(f, fieldnames=["name", "qty"]) and then writerows(items). The output file has data but no name,qty line at the top. Why, and how do you fix it?
Show answer
DictWriter does not write the header automatically. Call writer.writeheader() before writerows(items).