将Python字典和列表压缩在一起
是否可以压缩python字典并一起列出 例如:将Python字典和列表压缩在一起,python,list,dictionary,Python,List,Dictionary,是否可以压缩python字典并一起列出 例如: dict = {'A':1, 'B':2, 'C':3} num_list = [1, 2, 3] zipped = zip(dict, num_list) 然后我想做这样的事情: for key, value, num_list_entry in zipped: print key print value print num_list_entry 我还没有找到解决方案,所以我想知道如何着手做这件事?注意:不要隐藏内置的dict。这
dict = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dict, num_list)
然后我想做这样的事情:
for key, value, num_list_entry in zipped:
print key
print value
print num_list_entry
我还没有找到解决方案,所以我想知道如何着手做这件事?注意:不要隐藏内置的dict
。这终有一天会再次困扰你
现在,对于您的问题,只需使用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
>>>
注意:字典是没有顺序的,所以在对它们进行迭代时,不能保证项目的顺序
附加说明:当您迭代字典时,它会迭代键:
>>> for k in d:
... print(k)
...
A
C
B
这是一种常见的构造:
>>> for k in d.keys():
... print(k)
...
A
C
B
>>>
冗余,在Python 2中效率低下。您可以使用
iteritems()
你看过
zip
中的每个项目是什么吗?它们没有长度3,因此您无法将其解包为3个这样的名称。不要使用dict作为变量的名称,使用类似my_dict的坏习惯的名称“dict”作为您的字典。。。它隐藏了真正的dictdict
,这是一个内置函数名感谢您的回复。我试图在django应用程序中实现这一点,但for循环在模板中似乎不起作用。你知道为什么吗?在django模板中,你会这样做:{%fordictionary,num_list_条目在压缩%}{%with key=dictionary.0 value=dictionary.1%}{{key}}{{value}}{{num_list条目}{%endwith%}{%endfor%}
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