首页 > 解决方案 > Python:从“图”(数据库)数据递归创建字典

问题描述

A 在 MySQL 数据库中映射了一个层次结构(我通过 Peewee 访问)。我正在尝试遍历数据以将其重新组合成嵌套字典(最终转换为 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: {} } } } }

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

谢谢!

标签: pythonpython-3.xdictionaryrecursionpeewee

解决方案


使用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: {}}}}}}

推荐阅读