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_keys will 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)
Minimal example, writing directly to a file:
import jsonjson.dump(data, open(filename, 'wb'))data = json.load(open(filename))
or safely opening / closing:
import jsonwith open(filename, 'wb') as outfile: json.dump(data, outfile)with open(filename) as infile: data = json.load(infile)
If you want to save it in a string instead of a file:
import jsonjson_str = json.dumps(data)data = json.loads(json_str)