How to Save a Python Dictionary to a File in Python


If you need to save a Python Dictionary object type to a file using Python, then you can do one of the following:

Option 1 – Using pickle module

import pickle

my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23}

with open("dictionaryFile.pkl", "wb") as tf:
    pickle.dump(my_dict,tf)

Then you can load the pickle file back as follows:

import pickle

with open("dictionaryFile.pkl", "wb") as tf:
    new_dict = pickle.load(tf)

print(new_dict)

Option 2 – Using numpy

import numpy as np

my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23}
np.save('dictionaryFile.npy', my_dict)

Then you can load the file back as follows:

import numpy as np

new_dict = np.load('dictionaryFile.npy', allow_pickle='TRUE')
print(new_dict.item())

Option 3 – Using a json dump

import json

my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23}

tf = open("dictionaryFile.json", "w")
json.dump(my_dict,tf)
tf.close()

Then you can load the file back as follows:

import json

tf = open("dictionaryFile.json", "r")
new_dict = json.load(tf)
print(new_dict)