Skip to main content

How to Write a List of Dictionaries to a CSV File in Python with csv.DictWriter

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

When your data is a list of dictionaries, such as records from an API or a database, csv.DictWriter turns it into a CSV file: each dictionary becomes a row, and the column names come from a list you give it. This guide writes two people to people.csv on Python 3.15.2.

Syntax​

Syntax
import csv

with open(<file name>, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=<column names>)
writer.writeheader()
writer.writerows(<list of dictionaries>)
PartWhat it means
<file name>The CSV file to write, such as "people.csv". Mode "w" replaces a file that's already there
newline=""Leaves the line endings to the csv module
fieldnames=<column names>A list of the columns, in order, such as ["name", "city", "age"]. Every key in your dictionaries must be in it
writeheader()Writes the first row: the column names
writerows(<list of dictionaries>)Writes one row for each dictionary, its values in the order of fieldnames

The csv documentation describes DictWriter as "an object which operates like a regular writer but maps dictionaries onto output rows", and says a file you hand to the csv module "should be opened with newline=''".

The Example​

The script writes two people, each a dictionary with a name, a city and an age, to people.csv, and then prints the file it wrote.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

write_people.py
import csv

people = [
{"name": "Ana", "city": "Lisbon", "age": 34},
{"name": "Ben", "city": "Leeds", "age": 28},
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "city", "age"])
writer.writeheader()
writer.writerows(people)

with open("people.csv", encoding="utf-8") as file:
print(file.read(), end="")

The write_people.py script in a macOS-style code window: a list of two dictionaries with name, city and age, written to people.csv by csv.DictWriter with writeheader and writerows, and then read back and printed.

  • fieldnames sets the columns and their order.
  • writeheader() writes name,city,age as the first line.
  • writerows(people) writes one line per dictionary. The number 34 is written as the text 34, because a CSV file holds only text.
  • The second with block reads the finished file and prints it. end="" stops print from adding a blank line, since the file already ends with a line break.

Step 2: Run It​

Terminal
uv run python write_people.py
Output
name,city,age
Ana,Lisbon,34
Ben,Leeds,28

The terminal after uv run python write_people.py: the header line name,city,age, then Ana,Lisbon,34 and Ben,Leeds,28.

The header came from fieldnames, and each dictionary became one line, its values in the same column order. people.csv now sits next to the script. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
A dictionary has a key that fieldnames doesn't list, such as "email"ValueError: dict contains fields not in fieldnames: 'email'Add the key to fieldnames, or pass extrasaction="ignore" to leave extra keys out
Leaving out writeheader()The file starts with Ana,Lisbon,34, with no header lineCall writeheader() once, before the rows
Opening the file without newline=""The docs warn that on platforms that end lines with \r\n, "an extra \r will be added"Always pass newline=""

Troubleshooting​

SymptomLikely causeFix
ValueError: dict contains fields not in fieldnames: ...A dictionary has a key that isn't a columnList the key in fieldnames, or use extrasaction="ignore"
A row ends in an empty value, such as Cy,Oslo,That dictionary has no value for the last column, so DictWriter writes its restval, an empty string by defaultGive the dictionary the key, or set restval= to the value you want

FAQ​

What if a dictionary is missing one of the columns?​

DictWriter writes an empty value there. With the same fieldnames, the dictionary {"name": "Cy", "city": "Oslo"} becomes the line Cy,Oslo,. The docs: "The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames."

How do I skip keys I don't want in the file?​

Pass extrasaction="ignore". With fieldnames=["name", "city"] and extrasaction="ignore", the dictionary {"name": "Ana", "city": "Lisbon", "age": 34} is written as Ana,Lisbon.

How do I add rows to a file that already exists?​

Open it with "a" (append) instead of "w", and don't call writeheader() again. To write a single dictionary, use writer.writerow(...), which is writerows for one row.

Conclusion​

csv.DictWriter wrote the header from fieldnames and one line per dictionary, with the values in column order. Every key needs a column, or extrasaction="ignore", and the file needs newline="".

Additional Resources​