In this article, we will discuss how to create a csv file from a list of dictionaries in Python.
Table Of Contents
Introduction to Problem
Suppose we have a list of dictionaries. Like this,
# List of dictionaries listOfDict = [ {'Name' : 'Ritika', 'Age' : 27, 'City' : 'Delhi', 'Country' : 'India'}, {'Name' : 'Mark', 'Age' : 28, 'City' : 'Sydney', 'Country' : 'India'}, {'Name' : 'Suse', 'Age' : 29, 'City' : 'Las Vegas', 'Country' : 'India'}, {'Name' : 'Shaun', 'Age' : 30, 'City' : 'London', 'Country' : 'India'} ]
Now, we want to create a csv file from this list of dictionaries. Keys of the dictionaries should be the column names in the csv file. Whereas, values of each dictionary should be a row in the csv file. Contents of csv file should be like this,
Name,Age,City,Country Ritika,27,Delhi,India Mark,28,Sydney,India Suse,29,Las Vegas,India Shaun,30,London,India
Let’s see how to do this.
Frequently Asked:
Solution
Open the csv file in write mode, and get a file object. Pass the file object & list of column names to DictWriter() function of csv module, to get the DictWriter object. Then call the writeheader() function of DictWriter object to add the header in the csv file. Then call the writerows() function of DictWriter object with the list of dictionaries. It will add the values of each dictionary as a row in the csv file.
Let’s see an example,
import csv # List of dictionaries listOfDict = [ {'Name' : 'Ritika', 'Age' : 27, 'City' : 'Delhi', 'Country' : 'India'}, {'Name' : 'Mark', 'Age' : 28, 'City' : 'Sydney', 'Country' : 'India'}, {'Name' : 'Suse', 'Age' : 29, 'City' : 'Las Vegas', 'Country' : 'India'}, {'Name' : 'Shaun', 'Age' : 30, 'City' : 'London', 'Country' : 'India'} ] # Open the csv file in write mode with open('employees.csv', 'w') as fileObject: # Get a DictWriter object writerObj = csv.DictWriter( fileObject, fieldnames = listOfDict[0].keys()) # Add Header to csv file writerObj.writeheader() # Add rows in the csv file writerObj.writerows(listOfDict)
It will create a csv file employees.csv with the following contents,
Name,Age,City,Country Ritika,27,Delhi,India Mark,28,Sydney,India Suse,29,Las Vegas,India Shaun,30,London,India
Summary
We learned how to create csv file from a list of dictionaries in Python. Thanks.
Latest Video Tutorials