Open In App

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:

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:

filehandler = open(filename, 'wb')
pickle.dump(dictionary, filehandler)

Below is the implementation of the above methods.

Example 1: Writing to Text File




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")

Output:

Example 2: Appending to Text File




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")

Output:

Example 3: Writing using Pickle Module




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")

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


Article Tags :