如何转换字典元组,例如下面的示例:
({(1, 2): 3},
{(1, 3): 5},
{(1, 4): 5},
{(2, 4): 5},
{(1, 5): 10},
{(2, 6): 9},
{(1, 6): 9},
{(2, 1): 2},
{(2, 2): 3},
{(2, 3): 5},
{(2, 5): 10},
{(1, 1): 2})
像字典一样简单的形式:
{(1, 1): 2,
(1, 2): 3,
(1, 3): 5,
(1, 4): 5,
(1, 5): 10,
(1, 6): 9,
(2, 1): 12,
(2, 2): 7,
(2, 3): 7,
(2, 4): 3,
(2, 5): 4,
(2, 6): 2}
最佳答案 只需迭代元组并使用字典理解重建字典“flat”:
a = ({(1, 2): 3},
{(1, 3): 5},
{(1, 4): 5},
{(2, 4): 5},
{(1, 5): 10},
{(2, 6): 9},
{(1, 6): 9},
{(2, 1): 2},
{(2, 2): 3},
{(2, 3): 5},
{(2, 5): 10},
{(1, 1): 2})
b = {k:v for t in a for k,v in t.items()}
print(b)
结果:
{(1, 2): 3, (2, 6): 9, (2, 1): 2, (1, 1): 2, (1, 5): 10, (1, 3): 5, (1, 6): 9, (1, 4): 5, (2, 2): 3, (2, 3): 5, (2, 5): 10, (2, 4): 5}