[英]Convert a list of tuples to a dictionary
I have a list of tuples with three elements: 我有一个包含三个元素的元组列表:
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)],
]
I need to convert it to a dictionary in this format (note that the second element in the tuple will be the key): 我需要将其转换为这种格式的字典(请注意,元组中的第二个元素将是键):
A_dict = { 1: {2:72, 4:96},
2: {1:72, 4:80},
3: {},
4: {1:96, 2:80, 5:70},
5: {4:70},
}
Is there a way to convert A to A_dict? 有没有办法将A转换为A_dict?
I tried this: 我尝试了这个:
A_dict = {b:{a:c} for a,b,c in A}
but I got an error: 但我得到一个错误:
ValueError: not enough values to unpack (expected 3, got 2)
ValueError:没有足够的值可解包(预期3,得到2)
You can just do: 您可以这样做:
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}
}
By iterating on the indices of the list, according to its length. 通过根据列表的长度迭代列表的索引。 And for each value building its own dictionary:
并为每个值建立自己的字典:
A_dict = {i + 1 : {v[2] : v[0] for v in A[i]} for i in range(len(A))}
will output: 将输出:
{1: {2: 72, 4: 96},
2: {1: 72, 4: 80},
3: {},
4: {1: 96, 2: 80, 5: 70},
5: {4: 70}}
Actually your desired code is: 实际上,您想要的代码是:
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}
But that will 'skip' the third line, as there is no list, thus not able to determinate the actual key, according to your specification. 但这将“跳过”第三行,因为没有列表,因此根据您的规范无法确定实际的密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.