How can I use pickle to save a dict? How can I use pickle to save a dict? python python

How can I use pickle to save a dict?


Try this:

import picklea = {'hello': 'world'}with open('filename.pickle', 'wb') as handle:    pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)with open('filename.pickle', 'rb') as handle:    b = pickle.load(handle)print a == b


import pickleyour_data = {'foo': 'bar'}# Store data (serialize)with open('filename.pickle', 'wb') as handle:    pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)# Load data (deserialize)with open('filename.pickle', 'rb') as handle:    unserialized_data = pickle.load(handle)print(your_data == unserialized_data)

The advantage of HIGHEST_PROTOCOL is that files get smaller. This makes unpickling sometimes much faster.

Important notice: The maximum file size of pickle is about 2GB.

Alternative way

import mpuyour_data = {'foo': 'bar'}mpu.io.write('filename.pickle', data)unserialized_data = mpu.io.read('filename.pickle')

Alternative Formats

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python


# Save a dictionary into a pickle file.import picklefavorite_color = {"lion": "yellow", "kitty": "red"}  # create a dictionarypickle.dump(favorite_color, open("save.p", "wb"))  # save it into a file named save.p# -------------------------------------------------------------# Load the dictionary back from the pickle file.import picklefavorite_color = pickle.load(open("save.p", "rb"))# favorite_color is now {"lion": "yellow", "kitty": "red"}