如何将两个列表组合成Python中的字典? [英] How do I combine two lists into a dictionary in Python?
问题描述
我有两个相同长度的列表:
I have two lists of the same length:
[1,2,3,4]
和 [a,b,c,d]
我想创建一个我有 {1:a,2:b,3:c,4:d}
最好的方法是什么? / p>
What's the best way to do this?
推荐答案
dict(zip([1,2,3,4], [a,b,c,d]))
如果列表很大,你应该使用 itertools.izip
。
If the lists are big you should use itertools.izip
.
如果您的键多于值,并且要填充额外键的值,则可以使用 itertools.izip_longest
。
If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest
.
这里,一个
, b
, c
和 d
是变量 - 它可以正常工作(只要被定义),但你可能意味着 ['a','b','c','d']
如果你想要的话m作为字符串。
Here, a
, b
, c
, and d
are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d']
if you want them as strings.
zip
从每个迭代中获取第一个项,并创建一个元组,然后从每个元组中获取第二个项目等。
zip
takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.
一个href =http://docs.python.org/library/stdtypes.html#dict> dict
可以迭代迭代,其中每个内部迭代有两个项目 - 它然后使用第一个作为键,第二个作为每个项目的值。
dict
can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.
这篇关于如何将两个列表组合成Python中的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!