我有一个"查找"字典,它表示节点:
# 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()
如果非树图是合法的,循环的最后一部分将把它找到的值分配给position[val]
,而不是引发错误:
...
for val in vals:
if val in nodeindex:
position[val] = nodeindex[val]
else:
nodeindex[val] = position[val] = dict()