Easiest way to persist a data structure to a file in python?

file, persistence, python

Solution

Use the pickle module.

import pickle
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
afile = open(r'C:\d.pkl', 'wb')
pickle.dump(d, afile)
afile.close()

#reload object from file
file2 = open(r'C:\d.pkl', 'rb')
new_d = pickle.load(file2)
file2.close()

#print dictionary object loaded from file
print new_d

Problem

Let's say I have something like this: ``` d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } ``` What's the easiest way to progammatically get that into a file that I can load from python later? Can I somehow save it as python source (from within a python script, not manually!), then `import` it later? Or should I use JSON or something?

Original source