我有一个包含三个元素的元组列表:
A = [[(72, 1, 2), (96, 1, 4)],
[(72, 2, 1), (80, 2, 4)],
[],
[(96, 4, 1), (80, 4, 2), (70, 4, 5)],
[(70, 5, 4)],
]
我需要将其转换为这种格式的字典(请注意,元组中的第二个元素将是键):
A_dict = { 1: {2:72, 4:96},
2: {1:72, 4:80},
3: {},
4: {1:96, 2:80, 5:70},
5: {4:70},
}
是否可以将A转换为A_dict?
我尝试过:
A_dict = {b:{a:c} for a,b,c in A}
但我遇到了错误:
ValueError:没有足够的值可解压缩(预期3,得到2)
答案 0 :(得分:3)
您可以这样做:
A_dict = {k+1: {t[2]: t[0] for t in l} for k, l in enumerate(A)}
>>> A_dict
{
1: {2: 72, 4: 96},
2: {1: 72, 4: 80},
3: {},
4: {1: 96, 2: 80, 5: 70},
5: {4: 70}
}
答案 1 :(得分:2)
根据列表的长度迭代列表的索引。并为每个值建立自己的字典:
A_dict = {i + 1 : {v[2] : v[0] for v in A[i]} for i in range(len(A))}
将输出:
{1: {2: 72, 4: 96},
2: {1: 72, 4: 80},
3: {},
4: {1: 96, 2: 80, 5: 70},
5: {4: 70}}
实际上,您想要的代码是:
A_dict = {A[i][0][1] : {v[2] : v[0] for v in A[i]} for i in range(len(A)) if len(A[i]) > 0}
但这将“跳过”第三行,因为没有列表,因此无法根据您的规范确定实际的密钥。