【发布时间】:2020-06-26 19:01:59
【问题描述】:
我有一个嵌套字典如下:
{(1, 1): {'Transportation_Cost': 4},
(1, 2): {'Transportation_Cost': 5},
(1, 3): {'Transportation_Cost': 6},
(1, 4): {'Transportation_Cost': 8},
(1, 5): {'Transportation_Cost': 10},
(2, 1): {'Transportation_Cost': 6},
(2, 2): {'Transportation_Cost': 4},
(2, 3): {'Transportation_Cost': 3},
(2, 4): {'Transportation_Cost': 5},
(2, 5): {'Transportation_Cost': 8},
(3, 1): {'Transportation_Cost': 9},
(3, 2): {'Transportation_Cost': 7},
(3, 3): {'Transportation_Cost': 4},
(3, 4): {'Transportation_Cost': 2},
(3, 5): {'Transportation_Cost': 4}}
我想把它转换成一个像这样的平面字典:
{(1, 1): 4,
(1, 2): 5,
(1, 3): 6,
(1, 4): 8,
(1, 5): 10,
(2, 1): 6,
(2, 2): 4,
(2, 3): 3,
(2, 4): 5,
(2, 5): 8,
(3, 1): 9,
(3, 2): 7,
(3, 3): 4,
(3, 4): 2,
(3, 5): 4}
我希望有一个简单的函数可以使我的嵌套字典变平。我尝试了 here 中的 FlatDict 函数,但我不确定如何修改它,因为我的字典中有一个元组。
关于如何获得所需输出的任何建议?
【问题讨论】:
-
你能澄清一下到底是什么问题吗?你的代码在哪里?请参阅minimal reproducible example、How to Ask、help center。此外,除非绝对必要,否则请不要将信息作为图像共享。请参阅:meta.stackoverflow.com/questions/303812/…、idownvotedbecau.se/imageofcode、idownvotedbecau.se/imageofanexception。
标签: python dictionary tuples