Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 10

CSV Dicts — DictWriter and DictReader

Write dictionary rows to a CSV file with DictWriter and writeheader(), then read each row back as a dict with DictReader.

Intermediate25 min
CSV DictWriter and DictReader hero Module 16 Lesson 10

When each record is a dictionary, DictWriter and DictReader keep the column names attached to the values.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • csv.DictWriter and the fieldnames list
  • writeheader() and writerows()
  • csv.DictReader and the dict it yields
  • How to walk a row with m and p

The idea

Field names on the first row, values underneath

csv.writer thinks in lists. DictWriter thinks in dictionaries.

text
writer = csv.DictWriter(handle, fieldnames=names)

fieldnames is the column order. It becomes the header.

Method What it writes
writeheader() One row: the field names
writerows(records) One row per dict, values only, in field-name order
writerow(record) The same, for a single dict

The keys are not repeated on every data line. They live in the header. Each data line stores the values. If a dict is missing a field, that cell is empty. Extra keys that are not in fieldnames are not written unless you change the extras setting.

csv.DictReader(handle) reads a file that already has a header. Each iteration gives a dict. The header names become the keys.

Walk one row like any other dict: for m, p in row.items(). m is the field name. p is the value, still a string. Open the file in text mode with newline="", the same way as csv.writer.

Example

python
import csv

names = ["code", "label", "topic"]
records = [
    {"code": "W-21", "label": "Mina Cole", "topic": "CSV"},
    {"code": "W-22", "label": "Rowan Blake", "topic": "JSON"},
]
with open("contacts.csv", "w", newline="", encoding="utf-8") as handle:
    writer = csv.DictWriter(handle, fieldnames=names)
    writer.writeheader()
    writer.writerows(records)

with open("contacts.csv", "r", newline="", encoding="utf-8") as handle:
    for row in csv.DictReader(handle):
        for m, p in row.items():
            print(m, "-->", p)
        print("---")

The playground prints each field name and its value. The header is not printed as a data row because DictReader uses it as the keys.

Key takeaways

  • Pass fieldnames so the columns have a fixed order

  • writeheader() writes the keys once

  • writerows() writes the values of each dict

  • DictReader yields one dict per data row

  • Loop with for m, p in row.items()

  • Previous: csv.writer and csv.reader

  • Next: JSON load and dump

Loading playground…

Check your understanding

CSV DictWriter and DictReader quiz

DictWriter is for rows that are:

1 / 10