简体   繁体   English

如何通过组合两个列表中的项目来创建字典?

[英]How can I create a dictionary by combining items from two lists?

key_list=['number','alpha']
value_list=[['1','a'],['2','b']]

I want to collect elements in this pattern: 我想收集这种模式中的元素:

dict = {}
dict.setdefault(key_list[0],[]).append(value_list[0][0])
dict.setdefault(key_list[0],[]).append(value_list[1][0])
dict.setdefault(key_list[1],[]).append(value_list[0][1])
dict.setdefault(key_list[1],[]).append(value_list[1][1])

How to do this in loop? 如何在循环中执行此操作?

You can simply zip the values of the values_list and then zip the result with the key_list , with dictionary comprehension, like this 你可以简单地zip values_list的值,然后使用key_list zip结果,使用字典理解,就像这样

>>> {k: v for k, v in zip(key_list, zip(*value_list))}
{'alpha': ('a', 'b'), 'number': ('1', '2')}

You can understand this, step-by-step, like this 你可以像这样一步一步地理解这一点

>>> list(zip(*value_list))
[('1', '2'), ('a', 'b')]

Now, zip ping this with key_list will give us 现在,使用key_list对此进行zip ping将给我们

>>> list(zip(key_list, zip(*value_list)))
[('number', ('1', '2')), ('alpha', ('a', 'b'))]

Now, you can either use dict function to create the dictionary, like shown by mhawke, 现在,您可以使用dict函数创建字典,如mhawke所示,

>>> dict(zip(key_list, zip(*value_list)))
{'alpha': ('a', 'b'), 'number': ('1', '2')}

or use the dictionary comprehension, as I have shown above. 或者使用字典理解,如上所示。

zip() comes in very handy for this sort of thing: zip()对于这类事情非常方便:

key_list=['number','alpha']
value_list=[['1','a'],['2','b']]
d = dict(zip(key_list, zip(*value_list)))
print(d)

Output 产量

{'alpha': ('a', 'b'), 'number': ('1', '2')}

Basically this works by unpacking values_list so that the individual items (themselves lists) are passed as arguments to the zip() builtin function. 基本上这通过解压values_list工作,以便将各个项(它们自己的列表)作为参数传递给zip()内置函数。 This has the affect of collecting the numbers and alphas together. 这具有收集数字和alpha的效果。 That new list is then zipped with key_list to produce another list. 然后使用key_list压缩该新列表以生成另一个列表。 Finally a dictionary is created by calling dict() on the zipped list. 最后,通过在压缩列表上调用dict()来创建dict()

Note that this code does rely on the order of elements in value_list . 请注意,此代码确实依赖于value_list中元素的顺序。 It assumes that the numeric value always precedes the alpha value. 它假定数值始终在alpha值之前。 It also produces a dictionary of tuples not lists . 它还会生成一个元组字典而不是列表 If that is a requirement then using a dict comprehension (as per thefourtheye's answer) allows you to convert the tuples to lists as the dictionary is built: 如果这是一个要求,那么使用字典理解(根据thefourtheye的答案)允许您在构建字典时将元组转换为列表:

key_list=['number','alpha']
value_list=[['1','a'],['2','b']]
d = {k: list(v) for k, v in zip(key_list, zip(*value_list))}
>>> print(d)
{'alpha': ['a', 'b'], 'number': ['1', '2']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM