[英]Zipping a Python Dictionary and List together
Is it possible to Zip a python Dictionary and List together? 是否可以将python字典和列表一起压缩?
For Example: 例如:
dict = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dict, num_list)
Then I'd like to do something like this: 然后我想做这样的事情:
for key, value, num_list_entry in zipped:
print key
print value
print num_list_entry
I haven't found a solution for this, so I'm wondering how do I go about doing this? 我还没有找到解决方案,所以我想知道如何做到这一点?
You can use iteritems()
. 你可以使用
iteritems()
。
dictionary = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dictionary.iteritems(), num_list)
for (key, value), num_list_entry in zipped:
print key
print value
print num_list_entry
Note: do not shadow the built-in dict
. 注意: 不要阴影内置
dict
。 This will one day come back to haunt you. 这将有一天会回来困扰你。
Now, as for your issue, simply use dict.items
: 现在,至于你的问题,只需使用
dict.items
:
>>> d = {'A':1, 'B':2, 'C':'3'}
>>> num_list = [1, 2,3 ]
>>> for (key, value), num in zip(d.items(), num_list):
... print(key)
... print(value)
... print(num)
...
A
1
1
C
3
2
B
2
3
>>>
Note: Dictionaries aren't ordered, so you have no guarantee on the order of the items when iterating over them. 注意:字典不是订购的,因此在迭代它们时,您无法保证项目的顺序。
Additional Note: when you iterate over a dictionary, it iterates over the keys: 附加注意:当您遍历字典时,它会遍历键:
>>> for k in d:
... print(k)
...
A
C
B
Which makes this common construct: 这使得这个常见的结构:
>>> for k in d.keys():
... print(k)
...
A
C
B
>>>
Redundant, and in Python 2, inefficient. 冗余,在Python 2中,效率低下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.