列表列表中的字典理解 python

Dict Comprehension python from list of lists

我有一个列表列表,我正在尝试从列表中制作字典。我知道如何使用这种方法来做到这一点。 Creating a dictionary with list of lists in Python

我想要做的是使用第一个列表中的元素作为键来构建列表,而具有相同索引的其余项目将是值列表。但我不知道从哪里开始。每个列表的长度相同,但列表的长度不同

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]

resultDict = {'first':['A','1'],'second':['B','2'],'third':['C','3']}

如果你不关心列表和元组,它就像使用 zip 两次一样简单:

result_dict = dict(zip(example_list[0], zip(*example_list[1:])))

否则,您需要通过调用 map:

result_dict = dict(zip(example_list[0], map(list, zip(*example_list[1:]))))

zip 函数可能就是您要找的。

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]
d = {x: [y, z] for x, y, z in zip(*exampleList)}
print(d)
#{'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}

使用 zip(*exampleList) 解压值并使用键值对创建字典。

dicta = {k:[a, b] for k, a, b in zip(*exampleList)}
print(dicta)
# {'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}

如果更多列出:

dicta = {k:[*a] for k, *a in zip(*exampleList)}
# {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}

解包并使用 zip,然后使用字典理解来获取与第一个元素的映射,这似乎是可读的。

result_dict = {first: rest for first, *rest in zip(*exampleList)}

注意 exampleList 可以是任意长度的情况..

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3'],[4,5,6]]

z=list(zip(*exampleList[1:]))
d={k:list(z[i])  for i,k in enumerate(exampleList[0])}
print(d)

输出

{'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}