python - 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: {} } } } }
我确信这相当简单,但我对实现递归函数感到生疏。
谢谢!
解决方案
使用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: {}}}}}}
推荐阅读
- tableau-api - Tableau:使用 tabcmd 发布“仅仪表板”
- jenkins - npm publish 未使用私有 aws 代码工件存储库
- r - 如何覆盖收敛错误/警告以查看 R 中 lmer 中的模型输出
- amazon-web-services - 如何为 AWS Websocket API Gateway 添加自定义域?
- powershell - PowerShell - 日期时间格式更改
- python - 在 sympy 中与克罗内克三角洲签约
- python - python pandas从其他列表中找到关闭值并添加到新列
- json - 试图从Angular中的json数组中获取某些数据,我的方法只是抓取一些数据
- google-apps-script - 如何从 Apps-script 编辑器调用 Google CM360 API?
- .htaccess - .htaccess 将字符串重定向到匹配的子目录并发送索引文件