将列表列表转换为字典

时间:2019-01-17 02:01:48

标签: python python-3.x dictionary-comprehension

如何从列表的Python列表中创建字典,以便第一行是键,其余的是该键下的列表?

x = [['A', 'B', 'C'],
 [100, 90, 80],
 [88, 99, 111],
 [45, 56, 67],
 [59, 61, 67],
 [73, 79, 83],
 [89, 97, 101]]

目前,我对dict的理解是:

{i[0]: i[1:] for i in x}

{'A': ['B', 'C'],
 100: [90, 80],
 88: [99, 111],
 45: [56, 67],
 59: [61, 67],
 73: [79, 83],
 89: [97, 101]}

所需的结果是:

{
"A": [100, 88, 45, 59, 73, 89],
"B": [90, 99, 56, 61, 79, 97],
"C": [80, 111, 67, 83, 101],
}

如何正确理解字典理解?

2 个答案:

答案 0 :(得分:6)

您可以选择zip

wanted = {a[0]: list(a[1:]) for a in zip(*x)}

或者如果您熟悉拆箱:

wanted = {k: v for k, *v in zip(*x)}

答案 1 :(得分:0)

对于循环和列表理解:

x = [['A', 'B', 'C'],
[100, 90, 80],
[88, 99, 111],
[45, 56, 67],
[59, 61, 67],
[73, 79, 83],
[89, 97, 101]]
dict1={}

for i,k in  enumerate( x[0]):
    dict1[k]=[x1[i] for x1 in x[1:]]
print(dict1)
#{'A': [100, 88, 45, 59, 73, 89], 'B': [90, 99, 56, 61, 79, 97], 'C': [80, 111, 67, 67, 83, 101]}