You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何基于父子关系字典生成带层级缩进展示的树结构

实现方案

我们可以通过深度优先遍历(DFS)递归遍历父子字典的节点,按层级生成对应前缀即可实现需求,完整实现代码如下:

def build_tree(parent_dict, current_node, level=0):
    # 根节点层级为0,无需前缀
    if level == 0:
        print(current_node)
    else:
        # 每一层级加2个短横线,可根据需要调整前缀样式
        print(f"{'--' * level} {current_node}")
    # 遍历当前节点的所有子节点,递归生成下一层
    if str(current_node) in parent_dict:
        for child in parent_dict[str(current_node)]:
            build_tree(parent_dict, child, level + 1)

if __name__ == "__main__":
    # 输入的父子关系字典
    parent_dict = {
        '6690': [6620, 3618, 5547, 6660],
        '6620': [6303, 5199, 6293, 6597],
        '3618': [3616],
        '5547': [4137],
        '6660': [6621, 4138, 3558, 3556]
    }
    # 自动找到根节点:不存在于任何子节点列表中的父节点
    all_children = sum(parent_dict.values(), [])
    root = [k for k in parent_dict if int(k) not in all_children][0]
    # 生成树结构
    build_tree(parent_dict, root)

运行输出

6690
-- 6620
---- 6303
---- 5199
---- 6293
---- 6597
-- 3618
---- 3616
-- 5547
---- 4137
-- 6660
---- 6621
---- 4138
---- 3558
---- 3556

如果需要匹配示例里的特殊前缀长度,只需要修改'--' * level部分的生成逻辑即可,比如第一层子节点用3个短横线、第二层用4个,按需调整规则即可。

内容的提问来源于stack exchange,提问作者Antonio Cabras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:42:00