HOWTO · Python
How to Write Dictionary Into CSV in Python
It demonstrates how to write a dictionary into csv file in Python
On this page
Use Python’s standard csv module to write a dictionary to a CSV file. Choose writer() when each key-value pair should occupy one row; use DictWriter() when dictionaries share fields and should become records beneath a header.
Write one dictionary as key-value rows with csv.writer
A regular csv.writer writes sequences of values. Loop through a dictionary’s items and pass each key-value pair as a row to get two columns: one for the key and one for its value.
Run this example:
import csv
import tempfile
from pathlib import Path
record = {"Name": "John", "Age": "23", "Country": "USA"}
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "person.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
for key, value in record.items():
writer.writerow([key, value])
print(path.read_text(encoding="utf-8"), end="")
Name,John
Age,23
Country,USA
The rows have the form Name,John, Age,23, and Country,USA; this layout has no header row. The program writes to a temporary file, then prints the file contents. Opening with mode w creates a missing file and truncates an existing one immediately. Use append mode a if you need to preserve earlier rows, and decide how to handle a header before appending.
Write multiple dictionaries as records with csv.DictWriter
For a list of dictionaries with shared keys, DictWriter maps each dictionary to a record. Set fieldnames to the desired column order, write the header once, then write each dictionary as a row. The result has one header row followed by one row per dictionary.
import csv
import tempfile
from pathlib import Path
records = [
{"Name": "John", "Age": "23", "Country": "USA"},
{"Name": "Jose", "Age": "44", "Country": "Spain"},
]
fieldnames = ["Name", "Age", "Country"]
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "people.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(records)
print(path.read_text(encoding="utf-8"), end="")
Name,Age,Country
John,23,USA
Jose,44,Spain
The fieldnames sequence controls both header text and column order, regardless of the insertion order of keys in each record. Each dictionary should supply values for those fields. By default, DictWriter raises ValueError if a row contains an extra key; configure extrasaction="ignore" only when discarding extra data is intended. Missing keys are written using restval, which defaults to an empty string.
Choose file mode and handle write errors
Always open CSV text files with newline="" so the CSV module can manage line endings consistently. Mode w replaces prior contents; mode a adds rows at the end and creates the file if needed. In append mode, avoid writing the header again when the file already has one.
File operations can raise OSError, for example when a path is unavailable or access is denied. Catch it only when the program can respond usefully, such as by reporting the path and asking the user to choose another location. Do not treat catching an error as proof that a partial write was rolled back; inspect or replace the file if the application needs an all-or-nothing result.