key_list=['number','alpha']
value_list=[['1','a'],['2','b']]
我想收集这个模式中的元素:
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])
如何在循环中执行此操作?
最佳答案
zip()
对于这种事情非常方便:
key_list=['number','alpha']
value_list=[['1','a'],['2','b']]
d = dict(zip(key_list, zip(*value_list)))
print(d)
输出
{'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. This has the affect of collecting the numbers and alphas together. That new list is then zipped with key_list
to produce another list. Finally a dictionary is created by calling dict()
on the zipped list.
Note that this code does rely on the order of elements in value_list
. It assumes that the numeric value always precedes the alpha value. 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:
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']}
关于python - 如何通过组合两个列表中的项目来创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949284/