How to Convert a Python Dict to CSV with Header?

4.5/5 - (2 votes)

To convert a Python dictionary to a CSV file with header, call the csv.DictWriter(fileobject, fieldnames) method. Use the resulting writer object’s writer.writeheader() method without argument to write the header. This writes the list of column names passed as fieldnames, e.g., the dictionary keys obtained via dict.keys().

After writing the header, you can then call the DictWriter.writerow() method to write the rows.

Installing CSV

Before we look at an example, make sure to install the csv libray (if you haven’t already) by using the following command in your terminal/shell/command line:

pip install csv

🌍 More: How to Install a Library in Python?

Example – Simple Dict to CSV with Dict Keys as Headers

The following example writes the dictionary to a CSV using the dict keys as column names and the values as row values.

import csv

# Define the dictionary
data = {'A':'X1', 'B':'X2', 'C':'X3'}

# Open the file in writing mode
with open('my_file.csv', 'w', newline='') as f:

    # Create the writer with the dictionary keys as headers
    writer = csv.DictWriter(f, fieldnames=data.keys())

    # Write the header defined in the fieldnames argument

    # Write one or more rows

ℹ️ Note: We open the file using the newline='' argument to prevent some operating systems from inserting blank lines into the CSV.

The resulting file 'my_file.csv' looks like this:

🌍 Related Resource: 7 Best Ways to Convert Dict to CSV in Python

Example – List of Dicts to CSV with Dict Keys as Headers

You can convert a list of dicts to a CSV file in Python easily—by using the csv library. This is the most customizable of all four methods.

Here are the six easy steps to convert a list of dicts to a CSV with header row:

  1. Import the CSV library with import csv.
  2. Open the CSV file using the expression open('my_file.csv', 'w', newline=''). You need the newline argument because otherwise, you may see blank lines between the rows in Windows.
  3. Create a csv.DictWriter() object passing the file and the fieldnames argument.
  4. Set the fieldnames argument to the first dictionary’s keys using the expression salary[0].keys().
  5. Write the header using writer.writeheader()
  6. Write the list of dicts using writer.writerows()

Here’s the full code for copy&paste:

salary = [{'Name':'Alice', 'Job':'Data Scientist', 'Salary':122000},
          {'Name':'Bob', 'Job':'Engineer', 'Salary':77000},
          {'Name':'Carl', 'Job':'Manager', 'Salary':119000}]

# Method 2
import csv
with open('my_file.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=salary[0].keys())

Output file named 'my_file.csv' and located in the same folder:

Alice,Data Scientist,122000

You can customize the CSV writer in its constructor (e.g., by modifying the delimiter from a comma ',' to a whitespace ' ' character). Have a look at the specification to learn about advanced modifications.

There are many more ways to accomplish the same objective — please check out the following Finxter tutorial to learn how to use Pandas for that job!

🌍 Related Resource: How to Convert List of Dicts to CSV in Python