PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Python Save Dictionary To File

Python Save Dictionary To File

Updated on: January 5, 2023 | 4 Comments

In this lesson, you’ll learn how to save a dictionary to a file in Python. Also, we’ll see how to read the same dictionary from a file.

In this lesson, you’ll learn how to:

  • Use the pickle module to save the dictionary object to a file.
  • Save the dictionary to a text file.
  • Use the dump() method of a json module to write a dictionary in a json file.
  • Write the dictionary to a CSV file.

Table of contents

  • How to save a dictionary to file in Python
    • Example: save a dictionary to file
    • Read Dictionary from a File
  • Save a dictionary to a text file using the json module
  • Save the dictionary to a CSV file

How to save a dictionary to file in Python

Dictionaries are ordered collections of unique values stored in (Key-Value) pairs. The below steps show how to use the pickle module to save the dictionary to a file.

  1. Import pickle module

    The pickle module is used for serializing and de-serializing a Python object structure.

    Pickling” is the process whereby a Python object is converted into a byte stream, and “unpickling” is the inverse operation whereby a byte stream (from a binary file) is converted back into an original object.

    We can save a dictionary object as a serialized byte sequence into a file using the pickle module. Also, we can read them from a file into a Python script by unpickling them.

  2. Open a file in write/append binary mode.

    Whenever we write content into a file, we have to open the file in one of the specified access modes. Open a file using the built-in function called open(). This function takes two parameters, filename and access mode, and returns the file pointer.

    To open a binary file for writing, use the wb access mode. After you open the file for writing, the FileHandle is placed at the beginning of the file, and existing content will be truncated. A new file is created if the file doesn’t exist.

  3. Use the dump() method of the pickle module

    Now, we’ll use the dump() method to save the dictionary into a file.

    The dump() method writes the pickled representation of the Python object to the open file. In our case, The dictionary object gets converted into a byte stream.

  4. Read a dictionary from the file.

    Use a pickle module’s load() method to read the same dictionary from a file.

Example: save a dictionary to file

Let’s see the below example of how you can use the pickle module to save a dictionary to a person_data.pkl file.

import pickle

# create a dictionary using {}
person = {"name": "Jessa", "country": "USA", "telephone": 1178}
print('Person dictionary')
print(person)

# save dictionary to person_data.pkl file
with open('person_data.pkl', 'wb') as fp:
    pickle.dump(person, fp)
    print('dictionary saved successfully to file')Code language: Python (python)

Output:

Person dictionary
{'name': 'Jessa', 'country': 'USA', 'telephone': 1178}
dictionary saved successfully to file

Read Dictionary from a File

Now read the same dictionary from a file using a pickle module’s load() method.

Example:

import pickle

# Read dictionary pkl file
with open('person_data.pkl', 'rb') as fp:
    person = pickle.load(fp)
    print('Person dictionary')
    print(person)Code language: Python (python)

Output:

Person dictionary
{'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

Save a dictionary to a text file using the json module

We can use the Python json module to write dictionary objects as text data into the file. This module provides methods to encode and decode data in JSON and text formats.

We will use the following two methods of a json module.

  • The dump() method is used to write Python objects as JSON formatted data into a file.
  • Using the load() method, we can read JSON data from text, JSON, or a binary file to a dictionary object.

Let’s see the below example of how you can use the json module to save a dictionary to a text file.

import json

# assume you have the following dictionary
person = {"name": "Jessa", "country": "USA", "telephone": 1178}
print('Person dictionary')
print(person)

print("Started writing dictionary to a file")
with open("person.txt", "w") as fp:
    json.dump(person, fp)  # encode dict into JSON
print("Done writing dict into .txt file")Code language: Python (python)

Output:

Person dictionary
{'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

Started writing dictionary to a file
Done writing dict into .txt file
Person text file
Person text file

Note: You can also use the dump() method to write a dictionary in a json file. Only you need to change the file extension to json while writing it.

Read a dictionary from a text file.

Now, let’s see how to read the same dictionary from the file using the load() function.

import json

# Open the file for reading
with open("person.txt", "r") as fp:
    # Load the dictionary from the file
    person_dict = json.load(fp)

# Print the contents of the dictionary
print(person_dict)Code language: Python (python)

Output:

{'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

Save the dictionary to a CSV file

The Python csv library provides functionality to read from and write to CSV files.

  • Use the csv.DictReader() method to read CSV files into a dictionary.
  • Use the csv.DictWriter() method to write a dictionary to a CSV file.

Example: Save the dictionary to a CSV file.

import csv

# Dictionary to be saved
person = {"name": "Jessa", "country": "USA", "telephone": 1178}
print('Person dictionary')
print(person)

# Open a csv file for writing
with open("person.csv", "w", newline="") as fp:
    # Create a writer object
    writer = csv.DictWriter(fp, fieldnames=person.keys())

    # Write the header row
    writer.writeheader()

    # Write the data rows
    writer.writerow(person)
    print('Done writing dict to a csv file')Code language: Python (python)

Output:

Person dictionary
{'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

Done writing dict to a csv file
Person csv file
Person csv file

Example: Read a dictionary from a csv file

import csv

# Open the csv file for reading
with open("person.csv", "r") as infile:
    # Create a reader object
    reader = csv.DictReader(infile)

    # Iterate through the rows
    for row in reader:
        print(row)Code language: Python (python)

Output:

OrderedDict([('name', 'Jessa'), ('country', 'USA'), ('telephone', '1178')])

Note: This will read the contents of the person.csv file and create a dictionary for each row in the file. You can then iterate through the rows and access the values in the dictionary using the column names as keys.

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. ImageROBERT BLACK says

    February 5, 2024 at 2:54 am

    i am importing a configuration file in .py format
    I want to modify that file and save it. I will use the modified file later.

    Thanks

    Reply
    • ImageROBERT BLACK says

      February 5, 2024 at 2:54 am

      It is a dictionary file

      Reply
    • ImageROBERT BLACK says

      February 5, 2024 at 2:55 am

      it is a dictionay .py file.

      Reply
  2. Imagedavid gill says

    January 25, 2024 at 5:00 pm

    Hi, I am trying to save a dictionary to a CSV as per your code example. The dict successfully saves to a CSV but the format isn’t ideal; each key in my dictionary contains a list within which are 20 nested lists and within each of these are 11 nested lists. The csv successfully separates the data for each dict key into separate columns but all the data for that key is saved into a single row. How can I alter the python code to split the data into 20 rows for each key (the 20 nested lists) and then split each of the 11 nested lists into columns. i.e. data for a single dict key would be formatted into 11 columns x 20 rows. data for key 2 would follow suite from column 12 and so on. Thanks!!

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement
Advertisement