• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / List of Dictionaries to CSV in Python

List of Dictionaries to CSV in Python

Author: Aditya Raj
Last Updated: July 10, 2022

We use dictionaries in python to store key-value pairs. Similarly, we use a CSV file to store records that contain values for specific fields. In this article, we will discuss how we can convert a list of dictionaries to a CSV file in python.

List of Dictionaries to CSV in Python using csv.writer() 

The csv module provides us with different methods to perform various operations on a CSV file. To convert a list of dictionaries to csv in python, we can use the csv.writer() method along with the csv.writerow() method. For this, we will use the following steps.

  • First, we will open a csv file in write mode using the open() function. The open() function takes the file name as the first input argument and the literal “w” as the second input argument to show that the file will be opened in the write mode. It returns a file object that contains the empty csv file created by the open() function.
  • After opening the file, we will create a csv.writer object using the csv.writer() method. The csv.writer() method takes the file object as an input argument and returns a writer object. Once the writer object is created, we can add data from the list of dictionaries to the csv file using the csv.writerow() method.
  • The csv.writerow() method, when invoked on a writer object, takes a list of values and adds it to the csv file referred by the writer object.
  • First, we will add the header for the CSV file by adding the keys of a dictionary to the csv file. 
  • After adding the header, we will use a for loop with the writerow() method to add each dictionary to the csv file. Here, we will pass the values in the dictionary to the CSV file. 

After execution of the for loop, the data from the python dictionary will be added to the CSV file. To save the data, you should close the file using the close() method. Otherwise, no changes will be saved to the csv file.

The source code to convert a list of dictionaries to a csv file using the csv.writer() method is as follows.

import csv

listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
              {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
myFile = open('demo_file.csv', 'w')
writer = csv.writer(myFile)
writer.writerow(['Name', 'Roll', 'Language'])
for dictionary in listOfDict:
    writer.writerow(dictionary.values())
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()

Output:

THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript

List of Dictionaries to CSV in Python using csv.DictWriter() 

Instead of using the iterative method to add each dictionary to the csv file, we can convert the entire list of dictionaries to a CSV file at once. For this, we will use the DictWriter() method and the csv.writerows() method.

This approach differs from the previous method in the following steps.

  • Instead of creating a csv.writer object, we will create a csv.DictWriter object using the Dictwriter() method. The DictWriter() method takes the file object containing the csv file as its first argument and the name of the columns of the csv file as the second input argument. After execution, it returns a DictWriter object.  
  • After creating the DictWriter object, we will add the header to the csv file. For this, we will use the writeheader() method. The writeheader() method, when executed on a DictWriter object, adds the columns provided to the DictWriter() method as the header in the csv file.
  • After adding the header, we can add the entire list of dictionaries to the csv file using the writerows() method. The writerows() method, when invoked on a DictWriter object, takes a list of dictionaries as its input argument and adds the values in the dictionaries to the csv file.

After adding the entire list of dictionaries to the csv file, you must close the file using the close() method. Otherwise, no changes will be saved.

The source code for converting a list of dictionaries to csv file in python is given below.

import csv

listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
              {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
myFile = open('demo_file.csv', 'w')
writer = csv.DictWriter(myFile, fieldnames=['Name', 'Roll', 'Language'])
writer.writeheader()
writer.writerows(listOfDict)
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()

Output:

THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript

Conclusion

In this article, we have discussed two approaches to convert a list of dictionaries to csv file in python. In these approaches,  each dictionary will be added to the csv file irrespective of whether it has the same number of items as compared to the columns in the csv file or it has the same keys as compared to the column names in the csv file. Thus it is advised to make sure that each dictionary should have the same number of items. Also, You should make sure that the order of keys present in the dictionaries should be same. Otherwise, the data appended to the csv file will become inconsistent and will lead to errors. 

To know more about dictionaries in python, you can read this article on dictionary comprehension in python. You might also like this article on list comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us