从2清单制作字典 [英] Make Dictionary From 2 List
问题描述
可能重复:
将两个列表映射到Python字典中
试图用2个列表制作字典,一个是键,一个是值,但是我遇到了问题.这是我到目前为止的内容:
trying to make dictionary with 2 list one being the key and one being the value but I'm having a problem. This is what I have so far:
d={}
for num in range(10):
for nbr in range(len(key)):
d[num]=key[nbr]
说我的密钥是一个从1到9的列表,值列表是 [2,4,0,9,6,6,8,6,4,5]
我该如何分配它就像 {0:2,1:4等等...}
say my key is a list from 1 to 9 and value list is [2,4,0,9,6,6,8,6,4,5]
how do i assign so it that its like {0:2, 1:4, etc...}
推荐答案
zip()进行救援!
zip() to the rescue!
>>> k = range(1,10) # or some list or iterable of sorts
>>> v = [2,4,0,9,6,6,8,6,4,5]
>>> d = dict(zip(k,v))
>>> d
{1: 2, 2: 4, 3: 0, 4: 9, 5: 6, 6: 6, 7: 8, 8: 6, 9: 4}
>>>
有关更多详细信息,请参见 zip()内置函数 ,在Python文档中.
For more details, see zip() built-in function, in Python documentation.
注意,关于range()和键"列表.
该问题显示为"键是从1到9的列表"(即9个不同的键),但值列表显示了10个不同的值.这为讨论细节"的两点提供了机会:
Note, regarding range() and the list of "keys".
The question reads "key is a list from 1 to 9" (i.e. 9 distinct keys) but the value list shows 10 distinct values. This provides the opportunity to discuss two points of "detail":
- 上面的代码段中的range()函数将产生1到9的范围,这是因为始终包含起始值(此处为1)(如果提供),而结束值(此处为10)则永远不会包括在内.
- zip()函数在迭代之后停止,该迭代包括最短可迭代的最后一项(在我们的示例中,省略列表的最后一个值"5")
这篇关于从2清单制作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!