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

如何在未知内部结构时可视化Python中的嵌套字典内容?

未知层级嵌套字典的结构查看与可视化方案

一、文本化快速查看结构

1. 用Python自带的pprint模块

直接调用pprint.pprint(outer_dict),它会自动按缩进格式化嵌套层级,比手写基础遍历更省心。如果需要同时展示值的数据类型,可以用递归函数增强输出:

import pprint

def print_dict_with_type(d, indent=0):
    prefix = "  " * indent
    for k, v in d.items():
        if isinstance(v, dict):
            print(f"{prefix}{k}: [dict]")
            print_dict_with_type(v, indent+1)
        else:
            print(f"{prefix}{k}: {type(v).__name__} = {repr(v)}")

print_dict_with_type(outer_dict)

2. 用rich库生成带样式的树形输出

rich能输出带颜色的美观结构,安装后使用:

pip install rich
from rich.tree import Tree
from rich import print as rprint

def build_tree(tree, d):
    for k, v in d.items():
        if isinstance(v, dict):
            child = tree.add(f"[blue]{k}[/blue] (dict)")
            build_tree(child, v)
        else:
            tree.add(f"[green]{k}[/green]: {type(v).__name__} = {repr(v)}")

tree = Tree("outer_dict")
build_tree(tree, outer_dict)
rprint(tree)

二、图形化可视化方案

1. treelib生成结构化树形图

专门用于树形结构处理,可生成文本树或导出为图片(需额外安装graphviz):

pip install treelib
from treelib import Tree

def build_treelib(tree, parent_id, d):
    for k, v in d.items():
        node_id = f"{parent_id}.{k}"
        if isinstance(v, dict):
            tree.create_node(k, node_id, parent=parent_id)
            build_treelib(tree, node_id, v)
        else:
            tree.create_node(f"{k}: {type(v).__name__}", node_id, parent=parent_id)

tree = Tree()
tree.create_node("outer_dict", "root")
build_treelib(tree, "root", outer_dict)
tree.show()

# 若需导出图片,先安装graphviz后执行:
# tree.to_graphviz("dict_structure.dot")
# 再通过命令行转成png:dot -Tpng dict_structure.dot -o dict_structure.png

2. networkx+matplotlib绘制节点式树图

适合更直观的图形化展示:

pip install networkx matplotlib
import networkx as nx
import matplotlib.pyplot as plt

def add_edges(G, parent, d):
    for k, v in d.items():
        child = f"{parent}.{k}" if parent != "root" else k
        G.add_edge(parent, child)
        if isinstance(v, dict):
            add_edges(G, child, v)
        else:
            G.add_node(child, label=f"{k}: {type(v).__name__}")

G = nx.DiGraph()
G.add_node("root", label="outer_dict")
add_edges(G, "root", outer_dict)

pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=3000, node_color="lightblue")
labels = nx.get_node_attributes(G, 'label')
nx.draw_networkx_labels(G, pos, labels)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:32:24