How to Save Dictionary to a file in Python?

This article helps you to get to understand three important methods of saving the dictionary in Python.

source: https://www.i2tutorials.com/what-are-dictionaries-in-python/

What is dictionary?

Dictionary in Python is an unordered collection of data values, used to store data values like a map. It holds ‘key’, ‘value’ pairs.

simple dictionary is representation: {‘key1’:’value1’,….}

empty dictionary in python is {} or dict()

for example, let’s take the following dictionary to illustrate how to save it to a file:

a_dict = {'clk': 'click','cm': 'call me','cmb': 'call me back'}

keys: a_dict.keys()

dict_keys(['clk', 'cm', 'cmb'])

Using the save() function of numpy

import numpy as np
np.save(“a_dict.npy”, a_dict)

Using the dump() function of pickle

import pickle
with open(“a_dict.pkl”, “wb”) as f:
pickle.dump(a_dict,f)
f.close()

Using the dump() function of json

import json
with open(“a_dict.json”, “wb”) as t:
json.dump(a_dict,t)
f.close()

Reading the saved files respectively

read the .npy file

new_dict = np.load(‘a_dict.npy’, allow_pickle=’TRUE’)

read the .pkl file

with open(“a_dict.pkl”, “rb”) as f:
new_dict = pickle.load(f)
print(new_dict)

read the .json file

with open(“a_dictionary.json”, “rb”) as f:
new_dict = json.load(f)
print(new_dict)

Well, i believe that you learnt saving the dictionary to a file using these different methods and reading accordingly.

Keep following to get more resources that are very helpful to you!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mohamed Rizwan

Mohamed Rizwan

Data Scientist, Book Reviewer, Trainer, Script Writer. Loves to build NLP and Computer Vision based tools.