How to convert Python Dict to CSV

How to Convert Python Dict to CSV ? Step By Step Implementation

We can convert python dict to csv using CSV module and pandas module. CSV module use DictWriter and pandas firstly covert dict to dataFrame. Once we have the dataFrame, We can export the dataFrame to csv using to_csv() function.

Lets convert python dict to csv –

We will see the conversion using pandas and csv in different methods.

Method 1: Using CSV module-

Suppose we have a list of dictionaries which we need to export into a csv file. We will follow the below implementation.

1. Import the csv module.

import csv

 

2.create a dummy list of dict.

sample_dict = [
{'key1': 1, 'key2': 2, 'key3': 3},
{'key1': 4, 'key2': 5, 'key3': 6},
{'key1': 7, 'key2': 8, 'key3': 9},
]

 

3. Use DictWriter for writing the dicts into the list. Here we need to define the column name explicitly.

col_name=["key1","key2","key3"]
with open("export.csv", 'w') as csvFile:
        wr = csv.DictWriter(csvFile, fieldnames=col_name)
        wr.writeheader()
        for ele in sample_dict:
            wr.writerow(ele)

 

Here we can define the column name for the CSV. Suppose we have five keys in the dict. But we need to export only three, Then we will only define those three only. The above code will export the dict into export.csv

 

python dict to csv using csv module
python dict to csv using csv module

 

Method 2: Using the Pandas module-

 

Firstly, We will create dummy dict and convert it to dataFrame.  After it, We will export it to csv file using to_csv() function.

Step 1:

Here is the list of dicts with some sample data. We are also converting the dict to dataframe here.

import pandas as pd
sample_dict = [
{'key1': 1, 'key2': 2, 'key3': 3},
{'key1': 4, 'key2': 5, 'key3': 6},
{'key1': 7, 'key2': 8, 'key3': 9},
]
df = pd.DataFrame.from_dict(sample_dict) 

Step 2:

Let’s create the CSV out of the dataFrame.

df.to_csv (r'gen.csv', index = False, header=True)

Here index and header parameter are optional. In our scenario, We have used index as False and Header as True in the generated csv file.  we run the code together. It will generate gen.csv file.

 

Conclusion –

Well, These two are the most popular way to write dictionary to csv python. Personally, I found pandas way easier than csv module. Please tell which you found most convenient for this conversion. You may comment below at the comment box.

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner