我有这个代表节点的“查找”字典:
# Original "lookup" dictionary
{
0 : [1, 2],
2 : [3],
4 : [5]
}
...我希望以此为基础创建一个新字典,如下所示:
# New multidimensional dictionary
{
0 : {
1 : {},
2 : {
3 : {}
}
}
4 : {
5 : {}
}
}
}
如何使用递归实现这一点?
原始“查找”字典的键代表父节点,值代表一个或多个节点树中的子节点。
原始“查找”字典包含未知数量的键/值,深度未知。
请您参考如下方法:
我将假设此数据结构代表一棵树,并且节点已编号,因此父节点的索引始终低于子节点。然后,您可以借助辅助索引 (nodeindex) 构建您想要的树,而无需递归,它可以让您一步找到每个节点:
tree = dict()
nodeindex = dict()
for node, vals in sorted(lookup.items()):
if node not in nodeindex:
nodeindex[node] = tree[node] = dict() # insert at the top level
position = nodeindex[node]
for val in vals:
if val in nodeindex:
raise ValueError("Value (%d, %d) would create a loop!" %(node, val))
nodeindex[val] = position[val] = dict()
如果非 TreeMap 是合法的,则循环的最后一部分会将它找到的值分配给 position[val],而不是引发错误:
...
for val in vals:
if val in nodeindex:
position[val] = nodeindex[val]
else:
nodeindex[val] = position[val] = dict()
