如何使用泡菜保存字典?

本文翻译自:How can I use pickle to save a dict?

I have looked through the information that the Python docs give, but I'm still a little confused. 我已经仔细阅读了Python文档提供的信息,但仍然有些困惑。 Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it? 有人可以张贴示例代码来编写新文件,然后使用pickle将字典转储到其中吗?


#1楼

参考:https://stackoom.com/question/l4RB/如何使用泡菜保存字典


#2楼

Try this: 尝试这个:

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

#3楼

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normally it's preferable to use the cPickle implementation 通常,最好使用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.

#4楼

import pickle

dictobj = {'Jack' : 123, 'John' : 456}

filename = "/foldername/filestore"

fileobj = open(filename, 'wb')

pickle.dump(dictobj, fileobj)

fileobj.close()

#5楼

# 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"}

#6楼

I've found pickling confusing (possibly because I'm thick). 我发现酸洗令人困惑(可能是因为我很胖)。 I found that this works, though: 我发现这可行,但是:

myDictionaryString=str(myDictionary)

Which you can then write to a text file. 然后可以将其写入文本文件。 I gave up trying to use pickle as I was getting errors telling me to write integers to a .dat file. 我遇到错误并告诉我将整数写入.dat文件时,我放弃尝试使用pickle。 I apologise for not using pickle. 很抱歉没有使用泡菜。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值