如何转换这种类型的字典:
{"A":
{"B":{"w":0.4},
"C":{"w":0.6},
"D":{"w":0.8}},
"D":
{"C":{"w":0.2},
"A":{"w":0.8}}}
对于这种结构:
{"A":{"B":0.4,"C":0.6,"D":0.8},
"D":{"C":0.2,"A":0.8}}
谢谢
答案 0 :(得分:0)
给定
x = {
"A":{
"B":{"w":0.4},
"C":{"w":0.6},
"D":{"w":0.8}},
"D":{
"C":{"w":0.2},
"A":{"w":0.8}}}
你可以使用
w = {d:{i:x[d][i]['w'] for i in x[d]} for d in x}
或
g = lambda d: d['w'] if 'w' in d else {i:g(d[i]) for i in d}
w = g(x)
生成所需的结构。