我怎样才能用泡菜来保存字典?

我已经浏览了Python文档给出的信息,但是我仍然有点困惑。 有人可以发布示例代码,将写入一个新的文件,然后使用pickle转储字典到它?

尝试这个:

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 

由于Blender似乎不想将HIGHEST_PROTOCOL添加到他的答案中,所以这里有一个:

 import pickle your_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) 

HIGHEST_PROTOCOL的优点是文件变小了。 这使得有时候快速取出。

重要提示 :腌菜的最大文件大小约为2GB。

备择scheme

  • CSV:超简单格式( 读写 )
  • JSON:写出人类可读的数据很好, 非常常用( 读写 )
  • YAML:YAML是JSON的超集,但更容易阅读( 读写 , 比较JSON和YAML )
  • pickle:Python序列化格式( 读写 )
  • MessagePack ( Python包 ):更紧凑的表示( 读写 )
  • HDF5 ( Python包 ):很好的matrix( 读写 )
  • XML:也存在*叹*( 读写 )

对于您的应用程序,以下可能是重要的:

  • 支持其他编程语言
  • 阅读/写作performance
  • 紧凑(文件大小)

另请参阅: 数据序列化格式的比较

如果你正在寻找一种configuration文件的方式,你可能想阅读我的简短文章Pythonconfiguration文件

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

通常最好使用cPickle实现

 >>> import cPickle as pickle >>> help(pickle.dump) Help on built-in function dump in module cPickle: dump(...) dump(obj, file, protocol=0) -- Write an object in pickle format to the given file. See the Pickler docstring for the meaning of optional argument proto. 

一般来说,酸洗dict将会失败,除非你只有简单的对象,比如string和整数。

 Python 2.7.9 (default, Dec 11 2014, 01:21:43) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from numpy import * >>> type(globals()) <type 'dict'> >>> import pickle >>> pik = pickle.dumps(globals()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps Pickler(file, protocol).dump(obj) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump self.save(obj) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems save(v) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save rv = reduce(self.proto) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle module objects >>> 

即使是一个非常简单的dict往往会失败。 这只取决于内容。

 >>> d = {'x': lambda x:x} >>> pik = pickle.dumps(d) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps Pickler(file, protocol).dump(obj) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump self.save(obj) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems save(v) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 748, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle <function <lambda> at 0x102178668>: it's not found as __main__.<lambda> 

但是,如果使用更好的序列化程序(如dillcloudpickle ,则可以对大多数字典进行腌制:

 >>> import dill >>> pik = dill.dumps(d) 

或者,如果你想保存你的dict到一个文件…

 >>> with open('save.pik', 'w') as f: ... dill.dump(globals(), f) ... 

后面的例子与其他任何在这里发布的好答案是相同的(除了忽略dict的内容的可拣性以外)。

 import pickle dictobj = {'Jack' : 123, 'John' : 456} filename = "/foldername/filestore" fileobj = open(filename, 'wb') pickle.dump(dictobj, fileobj) fileobj.close() 

我发现酸洗混乱(可能是因为我很厚)。 我发现这个工作,但:

 myDictionaryString=str(myDictionary) 

然后你可以写入一个文本文件。 我放弃了尝试使用泡菜,因为我得到的错误告诉我写整数.dat文件。 我为不使用泡菜道歉。