简体   繁体   English

Python pickle:如何从pickle.loads读取键值对

[英]Python pickle: how to read key-values pairs from pickle.loads

I have a .pkl file that I'm writing with pickle, with key-value pairs and that works. 我有一个我正在用泡菜,键-值对编写的.pkl文件,并且可以正常工作。

However I was wondering how can I access the key-value pairs once I read from this file using pickle.load . 但是,我想知道一旦使用pickle.load从此文件中读取,如何访问键值对。

content = pickle.load(open(COOKIE_FILENAME, "rb"))

content is a dictionary ( <type 'dict'> ). content是一个字典( <type 'dict'> )。

If I do: 如果我做:

for key in content:
    # this works, but I don't have the values

What I want to do is instead something like: 我想做的是这样的:

for key, value in content:
    # do something with keys and values

but if I do that, I get: 但是如果我这样做,我会得到:

E ValueError: too many values to unpack E ValueError:太多值无法解压

The solution is: 解决方案是:

for key, value in content.items():
    # do something with keys and values

thanks @Jose, @roganjosh and @timgeb for your help via comments. 感谢@ Jose,@ roganjosh和@timgeb通过评论提供的帮助。

when doing: 做的时候:

for i in dict_object:

you actually iterate through keys and not values. 您实际上是遍历键而不是值。 to reach value just use 达到价值只是使用

dict_object[i]

just saying, but I think @ShinDarth 's answer is better 只是说而已,但我认为@ShinDarth的答案更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM