How to save a Python dictionary to a CSV file
Overview
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.
Syntax
df.to_csv("filname.csv")
Here, df is the data frame.
Parameters
The to_csv() method takes a filename with a path as a parameter.
Return value
It won't return anything, but creates a CSV file.
Code example
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"))
Code explanation
In the code snippet above, we do the following:
- Line 1: We import the
pandasmodule, which contains methods to create data frames and modify them. - Lines 4–7: We declare and initialize the dictionary
my_dictwith student names as keys and their ages as values. - Lines 10–12: We get the data frame from the dictionary
my_dictusing thepd.DataFrame()method. - Line 15: We save the data frame created above as a CSV file, using the
to_csv()method. We provide a mandatory parameter filename and an optional parameterindexwith a valueFalsefor not saving the index into the CSV file. - Line 18: We validate the saved CSV file by importing it using the
read_csv()method and print the result.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved