• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Dictionary / How To Save a Dictionary to File in Python

How To Save a Dictionary to File in Python

Author: Aditya Raj
Last Updated: May 5, 2022

A python dictionary is used to store key-value mappings in a program. Sometimes, we might need to store the dictionary directly in a file. In this article, we will discuss how we can save a dictionary directly to a file in Python.

Table of Contents
  • Save Dictionary to File Using Strings in Python
  • Save Dictionary to File in Binary Format in Python
  • Conclusion

Save Dictionary to File Using Strings in Python

 To save a dictionary into a file, we can first convert the dictionary into a string. After that, we can save the string in a text file. For this, we will follow the following steps.

  •  First, we will convert the dictionary into a string using the str() function. The str() function takes an object as input and returns its string representation. 
  • After obtaining the string representation of the dictionary, we will open a text file in write mode using the open() function. The open() function takes the file name and the mode as input arguments and returns a file stream object say myFile. 
  • After obtaining the file stream object myFile, we will write the string to the text file using the write() method. The write() method, when invoked on a file object, takes a string as an input argument and writes it to the file.
  • After execution of the write() method, we will close the file stream using the close() method.

By following the above steps, you can save a dictionary to a file in string form. After saving the dictionary to the file, you can verify the file content by opening the file. In the following code, we have first saved a python dictionary to a file.

myFile = open('sample.txt', 'w')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
myFile.write(str(myDict))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the dictionary is:")
print(myFile.read())

Output:

The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}

Save Dictionary to File in Binary Format in Python

Instead of storing the dictionary in the text format, we can directly store the dictionary in the binary format. For this, we will use the pickle module in Python. To save the dictionary to file using the pickle module, we will follow the following steps.

  • First, we will open a file in write binary (wb) mode using the open() function. The open() function takes the file name and the mode as input arguments and returns a file stream object say myFile.
  • The pickle module provides us with the dump() method with the help of which, we can save a dictionary in binary format to the file. The dump() method takes an object as its first input argument and a file stream as the second input argument. After execution, it saves the object to the file in binary format. We will pass the dictionary as the first argument and myFile as the second input argument to the dump() method. 
  • After execution of the dump() method, we will close the file using the close() method.

Following is the python code to save a dictionary to a file in python. 

import pickle

myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()

After saving the dictionary in the binary format, we can retrieve it using the load() method in the pickle module. The load() method takes the file stream containing the python object in binary form as its input argument and returns the Python object. After saving the dictionary to file using the dump() method, we can recreate the dictionary from the file as shown below.

import pickle

myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()
myFile = open('sample_file', 'rb')
print("The content of the file after saving the dictionary is:")
print(pickle.load(myFile))

Output:

The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}

Conclusion

In this article, we have discussed two ways to save a dictionary to a file in python. To know more about dictionaries, you can read this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Dictionary Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us