Python:从"graph"(数据库)数据递归创建字典

Python: Create dictionary recursively from "graph" (database) data

A 在 MySQL 数据库(我通过 Peewee 访问)中映射了一个层次结构。我正在尝试遍历数据以将其重新 assemble 放入嵌套字典中(最终转换为 XML)。

下面的函数将我的数据向下遍历到父节点并打印出我想要在我的字典中构建的数据:

def build_dict(current):
    query = (ParamLevel
            .select()
            # If we are looking for parents, we are matching on child
            .join(ParamLevelParamLevels, JOIN.LEFT_OUTER, on = (ParamLevelParamLevels.parent == ParamLevel.id))
            .where(ParamLevelParamLevels.child == current)
            )

    # If we have a parent node, recurse further
    if query.exists():
        parent = query.get()
        build_dict(parent)
        print('Current ParamLevel "%s" parent: "%s"' % ( current.name, parent.name ))
    else:
        print('Found root node: %s' % current.name)

这样做时,它会打印出:

Found root node: polycomConfig
Current ParamLevel "device" parent: "polycomConfig"
Current ParamLevel "device.dhcp" parent: "device"
Current ParamLevel "device.dhcp.bootSrvOptType" parent: "device.dhcp"

我正在寻找有关如何生成以下数据结构的输入:

{polycomConfig : { device : { device.dhcp : { device.dhcp.bootSrvOptType: {} } } } }

我确信这相当简单,但我对实现递归函数生疏了。

谢谢!

使用 while 循环而不是递归来完成它,并在你进行时构建嵌套的字典。在这种情况下,递归实际上没有任何好处。

def build_dict(current):
    print(f'Found root node {current.name}')
    temp_dict = {}
    query = (ParamLevel
            .select()
            # If we are looking for parents, we are matching on child
            .join(ParamLevelParamLevels, JOIN.LEFT_OUTER, on = (ParamLevelParamLevels.parent == ParamLevel.id))
            .where(ParamLevelParamLevels.child == current)
            )
    while query.exists():
        result = query.get()
        temp_dict = {result.name: temp_dict}
        query = (ParamLevel
            .select()
            # If we are looking for parents, we are matching on child
            .join(ParamLevelParamLevels, JOIN.LEFT_OUTER, on = (ParamLevelParamLevels.parent == ParamLevel.id))
            .where(ParamLevelParamLevels.child == result)
            )

没有办法测试它,我不能给你输出,也不能检查任何错误,但你应该了解它的要点。你想要的结果应该在temp_dict.

我用这个测试过:

d = {}
for i in range(5):
    d = {i: d}
print(d)

输出:

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

没有很好的例子很难尝试,但我相信这应该可行:

def build_dict(current, root={}):
    query = (
        ParamLevel.select()
        # If we are looking for parents, we are matching on child
        .join(
            ParamLevelParamLevels,
            JOIN.LEFT_OUTER,
            on=(ParamLevelParamLevels.parent == ParamLevel.id),
        ).where(ParamLevelParamLevels.child == current)
    )

    # If we have a parent node, recurse further
    if query.exists():
        parent = query.get()
        root, parent_dict = build_dict(parent, root)
        parent_dict[parent.name] = {current.name: {}}
        return root, parent_dict[parent.name]
    else:
        root[current.name] = {}
        return root, root

answer, _ = build_dict(<starting_node>)