如何在python中使用两个列表创建字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15183084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create a dictionary using two lists in python?
提问by Kara
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
I want to create a dictionary so the x and y values would correspond like this:
我想创建一个字典,以便 x 和 y 值对应如下:
1: [1,0], 2: [2,0]
and etc
等等
回答by Igonato
You can use zip function:
dict(zip(x, y))
您可以使用 zip 功能:
dict(zip(x, y))
>>> x = ['1', '2', '3', '4']
... y = [[1,0],[2,0],[3,0],[4,]]
>>> dict(zip(x, y))
0: {'1': [1, 0], '2': [2, 0], '3': [3, 0], '4': [4]}
回答by Makoto
You can use itertools.izipto accomplish this.
您可以使用它itertools.izip来完成此操作。
from itertools import izip
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
dict(izip(x, y))
If your flavor of Python is 3.x, then you can use itertools.zip_longestto do the same thing.
如果您的 Python 风格是 3.x,那么您可以使用itertools.zip_longest它来做同样的事情。
from itertools import zip_longest
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
dict(zip_longest(x, y))
回答by joaquin
In python > 2.7 you can use dict comprehension:
在 python > 2.7 中,您可以使用 dict 理解:
>>> x = ['1', '2', '3', '4']
>>> y = [[1,0],[2,0],[3,0],[4,]]
>>> mydict = {key:value for key, value in zip(x,y)}
>>> mydict
{'1': [1, 0], '3': [3, 0], '2': [2, 0], '4': [4]}
>>>
Still the best answer has already been given
最好的答案还是已经给出了
dict(zip(x, y))
字典(zip(x,y))
In python <= 2.7 you can use itertools.izipin case you work with big lists as izipreturns an iterator. For small lists like yours, the use of izipwould be overkilling. Note however that itertools.izipdissapeared in python 3. In python 3, the zipbuiltin already returns an iterator and in consequence izipwas not needed anymore.
在 python <= 2.7itertools.izip中,如果您使用大列表作为izip返回迭代器,则可以使用。对于像您这样的小列表,使用izip将是矫枉过正。但是请注意,它itertools.izip在 python 3中消失了。在 python 3 中,zip内置函数已经返回一个迭代器,因此izip不再需要。
回答by Snakes and Coffee
The quick and easy answer is dict(zip(x,y)), if you're ok with the keys being strings. otherwise, use dict(zip(map(int,x),y))
快速而简单的答案是dict(zip(x,y)),如果您认为键是字符串的话。否则,使用dict(zip(map(int,x),y))

