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

标签 python list dictionary

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/

相关文章:

python - Python 的程序数据库 (PDB) 符号

python - 打印回文数字的方 block : improve efficiency

python - 函数后两个空行

python - 如何从字符串列表创建多个变量?

python - 我想在Python中将分类变量转换为数值

javascript - 在javascript中的字典数组中搜索一个id

C# - 在 foreach 中更改字典键值对的值

python - 如何从两个平行字符串创建字典?

python - 如果子索引的列值满足条件,则从 MultiIndex 数据框中删除索引

查找频率最高的所有元素的 Pythonic 方法?