How to write lists and dictionaries into a CSV file with Python 3?

Problem:

To export a list or a dictionary to a comma (or tab) separated value file using Python code.

Solution:

CSV stands for Comma Separated Values, is a file format that stores tabular data in plain text, like a database or spreadsheet. Python provides an inbuilt module named CSV to read or write in CSV files. We have two modules provided in Python to write to CSV files: csv.writer() and csv.DictWriter(). We will look at each module with a sample example in this post.

Note that you can use the Pandas library Df.to_csv() method to write a Pandas DataFrame to csv/tsv file formats.

Write list with csv.writer()

The csv.writer() object allows to write both single or multiple rows:

  • writer.writerow() – For single row values.
  • writer.writerows() – For multiple row values.

Let’s see how we can use this in the code and write values to the CSV file.

Code:

import csv
myheaders = ['Name','EID','DOMAIN']
myvalues = [
    ['Akil',8901,'SUP'],
    ['John',7812,'DB'],
    ['Zoya',8034,'SUP'],
    ['Asha',1233,'DEV']
]
filename = 'employeedata.csv'
with open(filename, 'w', newline='') as myfile:
    writer = csv.writer(myfile)
    writer.writerow(myheaders)
    writer.writerows(myvalues)

Output:

Dictionary to CSV using csv.DictWriter()

The csv.DictWriter() is the same as the regular writer function but maps Python dictionaries into CSV rows. We have two functions enabled using the DictWriter().

  • writer.writeheader() – Takes the header values from the fieldname parameter specified in DictWriter().
  • writer.writerows() – It writes multiple row values specified. It takes only the key values.

Let’s see how we can use this in the code and write values to the CSV file.

Code:

import csv
myheaders = ['Name','EID','DOMAIN']
myvalues = [
    {'EID': 8901, 'Name':'Akil', 'DOMAIN': 'SUP'},
    {'EID': 7812, 'DOMAIN': 'DB', 'Name':'John'},
    {'Name':'Zoya','EID': 8034, 'DOMAIN': 'SUP'},
    {'EID': 1233, 'Name':'Asha', 'DOMAIN': 'DEV'},
]
filename = 'employeedata1.csv'
with open(filename, 'w', newline='') as myfile:
    writer = csv.DictWriter(myfile, fieldnames=myheaders)
    writer.writeheader()
    writer.writerows(myvalues)

Output:

Exporting Python lists to Pandas DataFrame

In today’s tutorial we just showed you how to convert your list or dictionary to CSV. If you are saving the data in CSV for Data Analysis purposes – you can simplify your workflow even further. Read our tutorial that shows how to convert a list or dictionary directly into a Pandas DataFrame for further analysis