Pickle a dictionary
Recently, I’ve found myself needing to save python dictionaries. I’m using it as a way of saving the “best” hyperparameters when working with Hyperopt (see my previous posts). The easiest way to do this in python seems to be using the “pickle” library. Writing (and later reading) a dictionary in this way looks like this.
import pickle # write with open('filename.pickle', 'wb') as f: pickle.dump(dictionary_to_save, f, pickle.HIGHEST_PROTOCOL) # read with open('filename.pickle', 'rb') as f: my_dictionary = pickle.load(f)
The handy thing about “with open…” is that it keep the file open only as long as needed — without you having to remember to close the file.