How to save a dictionary to a file? How to save a dictionary to a file? python-3.x python-3.x

How to save a dictionary to a file?


Python has the pickle module just for this kind of thing.

These functions are all that you need for saving and loading almost any object:

def save_obj(obj, name ):    with open('obj/'+ name + '.pkl', 'wb') as f:        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)def load_obj(name ):    with open('obj/' + name + '.pkl', 'rb') as f:        return pickle.load(f)

These functions assume that you have an obj folder in your current working directory, which will be used to store the objects.

Note that pickle.HIGHEST_PROTOCOL is a binary format, which could not be always convenient, but is good for performance. Protocol 0 is a text format.

In order to save collections of Python there is the shelve module.


Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:

import numpy as np# Savedictionary = {'hello':'world'}np.save('my_file.npy', dictionary) # Loadread_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()print(read_dictionary['hello']) # displays "world"

FYI: NPY file viewer


We can also use the json module in the case when dictionaries or some other data can be easily mapped to JSON format.

import json# Serialize data into file:json.dump( data, open( "file_name.json", 'w' ) )# Read data from file:data = json.load( open( "file_name.json" ) )

This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.