我的输入词典为: -
classDict = {'G1': ['V1', 'G3', 'V2'],
'G2': ['G4', 'V3'],
'G3': ['V2'],
'G4': ['V3'],
'G5': ['G6'],
'G6': ['G2', 'G4', 'V3'],
'G7': ['reset']
}
我需要将其转换为: -
finalStructure = {'G1': {'value':['V1','V2'],
'group':'G3'},
'G2': {'value':'V3',
'group':'G4'},
'G3': {'value':'V2'},
'G4': {'value':'V3'},
'G5': {'group':'G6'},
'G6': {'group':['G2', 'G4'],
'value':'V3'},
'G7': {'value':'reset'}
}
这里的问题是,dicts中的值也是某些地方的键。我需要找到它们,而不是将它们作为值添加到新字典中。这个问题背后的真正目的是创建平面类结构,其中V1,V2等是函数,G1,G2等是类。如果一个类G1在其组中有另一个类G3,那么它应该实例化该类。 请不要使用RE来区分“G”和“V”字符,因为它们只是伪名称,真实姓名完全不同。
答案 0 :(得分:1)
在这里。下次尝试自己实现一些东西。
def tofunnystructure(classDict):
finalStructure = {}
keys = set(classDict.keys())
for key, vals in classDict.iteritems():
newval = {}
value = [val for val in vals if val not in keys]
if value:
newval['value'] = value[0] if len(value) == 1 else value
groups = [val for val in vals if val in keys]
if groups:
newval['group'] = groups[0] if len(groups) == 1 else groups
finalStructure[key] = newval
return finalStructure
classDict = {'G1': ['V1', 'G3', 'V2'],
'G2': ['G4', 'V3'],
'G3': ['V2'],
'G4': ['V3'],
'G5': ['G6'],
'G6': ['G2', 'G4', 'V3'],
'G7': ['reset']
}
print tofunnystructure(classDict)
输出
{'G7':{'value':'reset'},'G6':{'group':['G2','G4'],'value':'V3'},'G5': {'group':'G6'},'G4':{'value':'V3'},'G3':{'value':'V2'},'G2':{'group':'G4' ,'价值':'V3'},'G1':{'group':'G3','value':['V1','V2']}}