如何根据查找字典创建未知深度的多维字典? (蟒蛇)

时间:2015-12-09 14:45:20

标签: python

我有这个“查找”字典,代表节点:

# Original "lookup" dictionary

{
  0 : [1, 2],
  2 : [3],
  4 : [5]
}

...我想基于此创建一个新词典,如下所示:

# New multidimensional dictionary

{
  0 : {
        1 : {},
        2 : {
              3 : {}
            }
      }
  4 : {
        5 : {}
      }
  }
}

如何使用递归实现这一目标?

原始“查找”字典的表示父节点,表示一个或多个节点树中的子节点。

原始的“查找”字典包含未知数量的键/值,深度未知。

1 个答案:

答案 0 :(得分:1)

我将假设此数据结构表示一个树,并且节点已编号,以便父节点的索引始终低于子节点。然后,您可以在没有递归的情况下构建所需的树,借助帮助程序索引(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()
相关问题