我有一个列表列表,我正在尝试从列表中创建一个字典。我知道如何使用这种方法。 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']}
答案 0 :(得分:3)
解包并使用zip
后跟dict理解来获取第一个元素的映射似乎是可读的。
result_dict = {first: rest for first, *rest in zip(*exampleList)}
答案 1 :(得分:2)
使用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]}
如果更多列出:
logout:
pattern: /logout
答案 2 :(得分:1)
如果您不关心列表与元组,那么就像使用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:]))))
答案 3 :(得分:1)
当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]}
答案 4 :(得分:0)
zip功能可能正是您要找的。 p>
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']}