Storing Python dictionaries

Pickle save:

try:    import cPickle as pickleexcept ImportError:  # python 3.x    import picklewith open('data.p', 'wb') as fp:    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:    data = pickle.load(fp)

JSON save:

import jsonwith open('data.json', 'w') as fp:    json.dump(data, fp)

Supply extra arguments like sort_keys or indent to get a pretty result. The argument sort_keyswill sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:    data = json.load(fp)