2017-10-06 135 views
2

我有一个列表的列表,我试图从列表中创建一本词典。我知道如何使用这种方法做到这一点。 Creating a dictionary with list of lists in PythonDict从列表清单中理解python

我想要做的就是使用第一个列表中的元素作为键构建列表,其余具有相同索引的项目将成为值列表。但我无法弄清楚从哪里开始。每个列表长度相同,但名单的长度变化

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

resultDict = {'first':['A','1'],'second':['B','2'],'third':['C','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]} 
+1

我刚刚添加的描述,因为名单的长度可以变化。 – mickNeill

1

如果你不关心名单VS元组,这是因为使用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:])))) 
0

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']} 
2

使用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]} 
3

拆封和使用zip之后的字典理解与第一要素来获取映射看起来可读。

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