The right way to Save a Python Dictionary to a File in Python
If you must save a Python Dictionary object sort to a file utilizing Python, then you are able to do one of many following:
Choice 1 – Utilizing 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 may load the pickle file again as follows:
import pickle
with open("dictionaryFile.pkl", "wb") as tf:
new_dict = pickle.load(tf)
print(new_dict)
Choice 2 – Utilizing numpy
#
import numpy as np
my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23}
np.save('dictionaryFile.npy', my_dict)
Then you may load the file again as follows:
import numpy as np
new_dict = np.load('dictionaryFile.npy', allow_pickle='TRUE')
print(new_dict.merchandise())
Choice 3 – Utilizing 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.shut()
Then you may load the file again as follows:
import json
tf = open("dictionaryFile.json", "r")
new_dict = json.load(tf)
print(new_dict)