Save a dictionary to a file

A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here.

Syntax:

dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}

Saving Dictionary to a File

There are two main approaches for saving dictionaries into files using Python.

1. Text Files

The most basic way to save dictionaries in Python would be to store them as strings in text files. This method would include the following steps:



  • Opening a file in write/append text mode
  • Converting the dictionary into a string
  • Entering the converted string into the file using write function
filehandler = open(filename, 'wt')
data = str(dictionary)
filehander.write(data)

Reading from the dictionary back from the stored text files is cumbersome and this method should only be used for smaller and non-critical programs.

2. Pickle Module (Recommended)

The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:

  • Importing the pickle module
  • Opening the file in write/append binary mode
  • Entering the data into the file using pickle module’s dump method
filehandler = open(filename, 'wb')
pickle.dump(dictionary, filehandler)

Below is the implementation of the above methods.

Example 1: Writing to Text File

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}
  
try:
    geeky_file = open('geekyfile.txt', 'wt')
    geeky_file.write(str(dictionary))
    geeky_file.close()
  
except:
    print("Unable to write to file")

chevron_right


Output:



Example 2: Appending to Text File

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}
  
try:
    geeky_file = open('geekyfile.txt', 'a')
    geeky_file.write(str(dictionary))
    geeky_file.close()
  
except:
    print("Unable to append to file")

chevron_right


Output:

Example 3: Writing using Pickle Module

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import pickle
  
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}
  
try:
    geeky_file = open('geekyfile', 'wb')
    pickle.dump(dictionary, geeky_file)
    geeky_file.close()
  
except:
    print("Something went wrong")

chevron_right


Note: As the pickle module stores data in binary form, the data in the file is unreadable by humans.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.