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:

with open('saved_dictionary.pkl', 'wb') as f:
    pickle.dump(dictionary, f)
        
with open('saved_dictionary.pkl', 'rb') as f:
    loaded_dict = pickle.load(f)

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

Leave a Comment