Sub topic 8
Working with named columns using DictReader and DictWriter
This chapter assumes you can write basic Python, work with dicts, lists, and strings, open files with the with statement, and handle exceptions. It also assumes you know the basics of csv.reader and csv.writer, and 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 reach values by position: row[0], row[2]. That breaks quietly when someone inserts a column, and the code is hard to read.
csv.DictReader and csv.DictWriter use the header row to give each column a name. You write row["qty"] instead of row[1]. The code documents itself, and it keeps working if the column order changes.
The sample file for this chapter is items.csv:
import csv
rows = [["name", "qty", "price"], ["apple", "3", "0.5"], ["pear, green", "5", "0.75"]]
with open("items.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)Reading with DictReader
DictReader wraps a file object. It reads the first row as the field names, then yields one dict per remaining row.
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
print(reader.fieldnames)
for row in reader:
print(row["name"], int(row["qty"]) * 2)Key points:
reader.fieldnamesis the list of column names. It is read from the file when you first access it or start iterating.- Every value is a string.
row["qty"]is"3", not3. Convert it yourself, as the next chapter covers in detail. - Since Python 3.8, each row is a regular
dict. Earlier versions returnedOrderedDict. Key order follows the column order. - The reader is an iterator. You can loop over it once. To loop again, reopen the file or collect the rows into a list.
Supplying your own field names
Some files have no header row. Pass fieldnames to name the columns yourself. In this case the first line is treated as data.
import csv
import io
raw = "apple,3,0.5\npear,5,0.75\n"
reader = csv.DictReader(io.StringIO(raw), fieldnames=["name", "qty", "price"])
for row in reader:
print(row)If the file has a header you want to replace, pass fieldnames and skip the first row with next(f) before building the reader.
Rows that do not match the header
Real files are messy. DictReader has defined behavior for rows with too many or too few fields.
| Situation | What DictReader does |
|---|---|
| Row has fewer values than the header | Missing keys get the `restval` value, which is `None` by default |
| Row has more values than the header | The extra values are stored in a list under the `restkey` key, which is `None` by default |
| Row is completely blank | The row is skipped |
The example below shows both cases.
import csv
import io
raw = "name,qty\napple\npear,5,extra,more\n"
reader = csv.DictReader(io.StringIO(raw), restkey="overflow", restval="")
for row in reader:
print(row)
# {'name': 'apple', 'qty': ''}
# {'name': 'pear', 'qty': '5', 'overflow': ['extra', 'more']}Setting restval="" gives you a string instead of None, which avoids a TypeError when you later call string methods or int() on the value. Setting restkey to a real name keeps the surplus data under a key you choose, instead of the key None.
Duplicate and messy headers
If two columns share a name, the later one overwrites the earlier one in each row dict. You lose data without any error. Spaces around header names also become part of the key, so " qty" is not "qty". Clean the names before you use them:
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
reader.fieldnames = [name.strip().lower() for name in reader.fieldnames]
for row in reader:
print(row["name"])Assigning to fieldnames after creation works because the reader looks the names up each time it builds a row. Access reader.fieldnames first so the header is read before you replace it.
A file that starts with a UTF-8 byte order mark (BOM), often written by Excel, makes the first header read as "\ufeffname". Open such files with encoding="utf-8-sig" so the mark is removed.
Writing with DictWriter
DictWriter converts dicts into CSV rows. Unlike DictReader, it needs the column names up front, because dicts do not guarantee that every record has every key.
import csv
items = [
{"name": "apple", "qty": 3, "price": 0.5},
{"name": "pear, green", "qty": 5, "price": 0.75},
]
with open("items_out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "qty", "price"])
writer.writeheader()
writer.writerows(items)Things to know:
fieldnamessets both the header text and the column order in the output. The order of keys inside each dict does not matter.writeheader()is not automatic. If you forget it, the file has no header row.- Values are converted with
str(). Numbers are written as text, andNoneis written as an empty field. writerow(dict)writes one record.writerows(iterable_of_dicts)writes many.- The writer quotes fields as needed, so
"pear, green"is written with quotes and reads back as one value.
Missing and extra keys
DictWriter is strict by default about keys that are not in fieldnames, and lenient about keys that are missing.
| Situation | Default behavior | Controlled by |
|---|---|---|
| A dict lacks a key listed in `fieldnames` | The field is written as the `restval` value, which is an empty string | `restval` |
| A dict has a key not in `fieldnames` | `ValueError` is raised | `extrasaction` |
Set extrasaction="ignore" to drop unknown keys silently. This is useful when you write a subset of columns from richer records.
import csv
import sys
records = [
{"name": "apple", "qty": 3, "internal_id": 991},
{"name": "pear", "internal_id": 992},
]
writer = csv.DictWriter(
sys.stdout,
fieldnames=["name", "qty"],
restval="0",
extrasaction="ignore",
lineterminator="\n",
)
writer.writeheader()
writer.writerows(records)This prints:
name,qty
apple,3
pear,0The internal_id key is dropped, and the missing qty in the second record becomes 0. Here lineterminator="\n" is only for clean console output. For real files, keep the default and open the file with newline="".
A round trip: read, change, write
A common task is to read a file, change some values, and write a new file. Because DictReader returns strings, convert before you calculate, then let DictWriter turn the results back into text.
import csv
with open("items.csv", newline="", encoding="utf-8") as src, \
open("items_priced.csv", "w", newline="", encoding="utf-8") as dst:
reader = csv.DictReader(src)
fields = reader.fieldnames + ["total"]
writer = csv.DictWriter(dst, fieldnames=fields)
writer.writeheader()
for row in reader:
row["total"] = int(row["qty"]) * float(row["price"])
writer.writerow(row)The output columns are the input columns plus total. Rows are processed one at a time, so memory use stays flat even for a large input file. Never use the same path for src and dst. Opening it for writing truncates the file before you read it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'qty'` | Header has different spelling, case, or whitespace, or a BOM | Print `reader.fieldnames`, normalize names, use `utf-8-sig` |
| `ValueError: dict contains fields not in fieldnames` | A record has an extra key | Add the column to `fieldnames` or use `extrasaction="ignore"` |
| Output has no header | `writeheader()` was not called | Call it once before writing rows |
| Blank line between every row on Windows | File was opened without `newline=""` | Open with `newline=""` |
| `TypeError` on arithmetic | Values are still strings | Convert with `int()` or `float()` |
| Second loop over the reader produces nothing | The reader is exhausted | Reopen the file or store rows in a list |
When to use dict-based access
Choose DictReader and DictWriter when the file has a header and you refer to columns by meaning. Their cost is small: each row builds a dict, which uses somewhat more memory and time than a list. For files with tens of millions of rows and a fixed layout, csv.reader may be noticeably faster. For almost all scripts, readability wins.
Exercise
A file people.csv has the header name,age and the rows Ana,31 and Bo. You read it with csv.DictReader(f, restval="unknown"). What does the second row look like, and what does row["age"] + 1 do for the first row?
Show answer
The second row is {'name': 'Bo', 'age': 'unknown'}, because the missing field gets the restval value. For the first row, row["age"] is the string "31", so row["age"] + 1 raises TypeError (you cannot add an int to a str). Use int(row["age"]) + 1 instead.
Exercise
You call writer.writerow({"name": "kiwi", "qty": 2, "color": "green"}) on a DictWriter created with fieldnames=["name", "qty"]. What happens, and how do you change it so the row is written without the color column?
Show answer
It raises ValueError because color is not in fieldnames. Create the writer with extrasaction="ignore" to drop unknown keys, or add "color" to fieldnames if you want that column in the output.