尝试这个:
import pickle
a = {'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)
上述解决方案没有任何特定于dict
目的。同样的方法适用于许多 Python 对象,包括任意类的实例和任意复杂的数据结构嵌套。例如,将第二行替换为以下行:
import datetime
today = datetime.datetime.now()
a = [{'hello': 'world'}, 1, 2.3333, 4, True, "x",
("y", [[["z"], "y"], "x"]), {'today', today}]
将产生以下结果True
以及。
有些物体由于其本质而无法腌制。例如,pickle 包含打开文件句柄的结构是没有意义的。