In Python, a dictionary is a data structure that contains key-value pairs separated by commas. We might want to export the results of a dictionary as a CSV file. In this Answer, we will learn how to save a Python dictionary as a CSV file.
Using the pandas library is one of the easiest ways to convert a Python dictionary to a CSV file.
df.to_csv("filname.csv")
Here, df
is the data frame.
The to_csv()
method takes a filename with a path as a parameter.
It won't return anything, but creates a CSV file.
Let's take a look at an example of this.
import pandas as pd#create dictionary of studentsmy_dict = {"Student": ['John', 'Lexi', 'Augustin', 'Jane', 'Kate'],"Age": [18, 17, 19, 17, 18]}#create data frame from dictionaryclassA = pd.DataFrame(my_dict)#save dataframe to csv fileclassA.to_csv("student.csv", index=False)#validate the csv file by importing itprint(pd.read_csv("student.csv"))
In the code snippet above, we do the following:
pandas
module, which contains methods to create data frames and modify them.my_dict
with student names as keys and their ages as values.my_dict
using the pd.DataFrame()
method.to_csv()
method. We provide a mandatory parameter filename and an optional parameter index
with a value False
for not saving the index into the CSV file.read_csv()
method and print the result.Free Resources