How to Convert List of dictionaries to CSV in Python: 4 Steps

If you have a list of dictionary and wants to convert or export it to a CSV file then this post is for you. In this tutorial, you will know how to convert a list of dictionaries to CSV in python through steps.

Syntax of the Function Used

In this post, we have used one DataFrame() constructor and to_csv() function. The syntax is below.

pandas.DataFrame(your_list_of_dictionaries)
to_csv("name_of_csv_file.csv")

Steps to convert a list of dictionaries to CSV in python

Step 1: Import the pandas module

Import the pandas module using the import statement.

import pandas as pd

Step 2: Create a List of dictionaries

In this step, we will create a sample list of dictionaries that will be used to convert a list of dictionaries to CSV.

list_of_dicts = [
  {
    "country": "USD",
    "capital": "Washington DC",
    "dial_code": 1
  },
  {
    "name": "UK",
    "capital": "London",
    "dial_code": 44
  }
]

Step 3: Create the dataframe

You will convert the list of dictionaries to dataframe using the pd.DataFrame() constructor. Pass the list of dictionaries to it.

df = pd.DataFrame(list_of_dicts)

Step 4: Export the dataframe

Now the last step is to export the converted list of dictionaries to a CSV file using the dataframe.to_csv() function.

df.to_csv("list_of_dict_to_csv.csv")

That is all you have to do is convert a list of dictionaries to CSV in python.

Full Code

import pandas as pd
list_of_dicts = [
  {
    "country": "USD",
    "capital": "Washington DC",
    "dial_code": 1
  },
  {
    "name": "UK",
    "capital": "London",
    "dial_code": 44
  }
]

df = pd.DataFrame(list_of_dicts)
df.to_csv("list_of_dict_to_csv.csv")

Output

list of dictionary to csv in python
list of dictionary to csv in python

Summary

In this tutorial, you have known the syntax of the pd.DataFrame() constructor and to_csv() function. After that, you imported the pandas module to first convert the list of dictionaries to dataframe. Lastly used the to_csv() function to export the dataframe to a CSV file.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link