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

Problem:

To export a list or a dictionary to a CSV 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. Namely csv.writer() and csv.DictWriter(). We will look at each module with a sample example in this post. You can use the Pandas library Df.to_csv() method to write a dataframe to csv/tsv fomats.

Write list with csv.writer()

The csv.writer() would create a writer object which enables the two functions:

  • 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: