如何在 Python 中将两个列表组合成一个字典? [英] How do I combine two lists into a dictionary in Python?

查看:37
本文介绍了如何在 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}

I want to create a dictionary where I have {1:a, 2:b, 3:c, 4:d}

最好的方法是什么?

推荐答案

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.

这里,abcd 是变量——它会正常工作(只要它们被定义),但你可能是指 ['a','b','c','d'] 如果你想要它们作为字符串.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆