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

1
2
3
4
5
6
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:

1
2
3
4
5
6
import pickle

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

print(new_dict)

Option 2 – Using numpy

1
2
3
4
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:

1
2
3
4
import numpy as np

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

Option 3 – Using a json dump

1
2
3
4
5
6
7
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:

1
2
3
4
5
import json

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