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.
We will see the conversion using pandas and CSV in different methods.
Suppose we have a list of dictionaries that we need to export into a CSV file. We will follow the below implementation.
The first step is to import python module for CSV and it is csv.
import csv
For converting dict to csv lets create a sample list of dict. You can use your own dict.
sample_dict = [
{'key1': 1, 'key2': 2, 'key3': 3},
{'key1': 4, 'key2': 5, 'key3': 6},
{'key1': 7, 'key2': 8, 'key3': 9},
]
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 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
Firstly, We will create a dummy dict and convert it to dataFrame. After it, We will export it to a CSV file using the to_csv() function.
Here is the list of dicts with some sample data. It will be used for 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)
Let’s create the CSV out of the dataFrame.
df.to_csv (r'gen.csv', index = False, header=True)
Here index and header parameters are optional. In our scenario, We have used index as False and Header as True in the generated CSV file. When we run the code together. It will generate a gen.csv file.
Well, These two are the most popular way to write a dictionary to CSV python. Personally, I found pandas way easier than CSV module. Please tell me which you found most convenient for this conversion. You may comment below at the comment box.
Thanks
Data Science Learner Team