我正在尝试将键与唯一标识符相关联。也就是将 dict1 转换为 dict2:
dict1={'A': {'A': 1},
'B': {'B': .5, 'C': .36, 'E': .14},
'C': {'A': .5, 'C': .5},
'D': {'G': 1},
'E': {'F': 1},
'F': {}
}
dict2={1: {1: 1},
2: {2: .5, 3: .36, 5: .14},
3: {1: .5, 3: .5},
4: {7: 1},
5: {6: 1},
6: {}
}
我递归地想出了一些东西,但我的代码对于嵌套键来说效果不太好。有关如何修复代码或解决此问题的任何建议?
def transform(d, count = 1):
output={}
for k,v in d.iteritems():
k=count
count = count + 1
if isinstance(v,dict):
v=transform(v, count)
output[k]=v
return output