Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to save a Python dictionary to a CSV file

Gutha Vamsi Krishna

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 students
my_dict = {
      "Student": ['John', 'Lexi', 'Augustin', 'Jane', 'Kate'],
      "Age": [18, 17, 19, 17, 18]
   }

#create data frame from dictionary
classA = pd.DataFrame(
   my_dict
)

#save dataframe to csv file
classA.to_csv("student.csv", index=False)

#validate the csv file by importing it
print(pd.read_csv("student.csv"))
Save a Python dictionary to a CSV file

Code explanation

In the code snippet above, we do the following:

  • Line 1: We import the pandas module, which contains methods to create data frames and modify them.
  • Lines 4–7: We declare and initialize the dictionary my_dict with student names as keys and their ages as values.
  • Lines 10–12: We get the data frame from the dictionary my_dict using the pd.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 parameter index with a value False for 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.

RELATED TAGS

python

CONTRIBUTOR

Gutha Vamsi Krishna
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring