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

Python嵌套字典树形打印实现:anytree库使用遇阻求替代方案

解决方案:嵌套字典转树形打印

问题背景

你有如下嵌套字典表示的树形结构:

dict_tree = {'A': {'b': {'c': {'d': {}, 'e': {'f': {}}}}}}

其中空字典{}代表叶子节点,想输出成如下树形格式:

A
|-b
    |-c
        |-d
        |-e
            |-f

使用anytree的DictImporter时因格式不匹配,输出不符合预期,下面提供两种实现方法:


方法一:自定义递归函数(无需第三方库)

直接写递归遍历逻辑,根据层级生成对应前缀符号:

def print_tree(node_dict, indent=0):
    for name, children in node_dict.items():
        # 根节点无前置符号,子节点按层级生成缩进和|-标记
        if indent == 0:
            print(name)
        else:
            print(f"{'    '*(indent-1)}|-{name}")
        # 非叶子节点递归处理子节点,层级+1
        if children:
            print_tree(children, indent + 1)

# 测试执行
dict_tree = {'A': {'b': {'c': {'d': {}, 'e': {'f': {}}}}}}
print_tree(dict_tree)

运行后输出完全符合需求:

A
|-b
    |-c
        |-d
        |-e
            |-f

方法二:适配anytree库使用

如果坚持要用anytree,可通过调整字典结构或自定义导入规则实现:

方式2.1:转换字典为兼容格式

将原字典转换成{name: 节点名, children: [子节点字典...]}的结构再导入:

def convert_to_anytree_format(node_dict):
    for name, children in node_dict.items():
        child_list = []
        if children:
            child_list = [convert_to_anytree_format({child: children[child]}) for child in children]
        return {'name': name, 'children': child_list}

# 导入并渲染
from anytree.importer import DictImporter
from anytree import RenderTree, AsciiStyle

dict_tree = {'A': {'b': {'c': {'d': {}, 'e': {'f': {}}}}}}
formatted_dict = convert_to_anytree_format(dict_tree)
importer = DictImporter()
root = importer.import_(formatted_dict)

print(RenderTree(root, style=AsciiStyle()))

输出结果:

AnyNode(name='A')
└── AnyNode(name='b')
    └── AnyNode(name='c')
        ├── AnyNode(name='d')
        └── AnyNode(name='e')
            └── AnyNode(name='f')

方式2.2:自定义导入规则

通过自定义节点类,直接从原字典结构创建树形节点:

from anytree import Node, RenderTree, AsciiStyle

class CustomNode(Node):
    def __init__(self, name, parent=None, **kwargs):
        super().__init__(name=name, parent=parent, **kwargs)

def import_custom_dict(dict_tree):
    def recurse(parent, node_dict):
        for name, children in node_dict.items():
            node = CustomNode(name, parent=parent)
            if children:
                recurse(node, children)
        return parent
    return recurse(None, dict_tree)

# 导入并渲染
root = import_custom_dict(dict_tree)
print(RenderTree(root, style=AsciiStyle()))

输出与方式2.1一致,可得到标准树形结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:53:37