Skip to content

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)
Code language: Python (python)

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)
Code language: Python (python)

Option 2 – Using numpy

import numpy as np my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23} np.save('dictionaryFile.npy', my_dict)
Code language: Python (python)

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())
Code language: Python (python)

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()
Code language: Python (python)

Then you can load the file back as follows:

import json tf = open("dictionaryFile.json", "r") new_dict = json.load(tf) print(new_dict)
Code language: Python (python)

See also  How to Create a MySQL Database in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x