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 writer.writeheader() # Write one or more rows writer.writerow(data)
βΉοΈ 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:
- Import the CSV library with import csv.
- 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. - Create a
csv.DictWriter()
object passing the file and thefieldnames
argument. - Set the
fieldnames
argument to the first dictionary’s keys using the expressionsalary[0].keys()
. - Write the header using
writer.writeheader()
- 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()) writer.writeheader() writer.writerows(salary)
Output file named 'my_file.csv'
and located in the same folder:
Name,Job,Salary
Alice,Data Scientist,122000
Bob,Engineer,77000
Carl,Manager,119000
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