Python 官方文档:入门教程 => 点击学习
目录python字典生成树状图Python生成树结构python字典生成树状图 from graphviz import Digraph # 获取所有节点中最多子节点的叶节点 de
from graphviz import Digraph
# 获取所有节点中最多子节点的叶节点
def getMaxLeafs(myTree):
numLeaf = len(myTree.keys())
for key, value in myTree.items():
if isinstance(value, dict):
sum_numLeaf = getMaxLeafs(value)
if sum_numLeaf > numLeaf:
numLeaf = sum_numLeaf
return numLeaf
def plot_model(tree, name):
g = Digraph("G", filename=name, fORMat='png', strict=False)
first_label = list(tree.keys())[0]
g.node("0", first_label)
_sub_plot(g, tree, "0")
leafs = str(getMaxLeafs(tree) // 10)
g.attr(rankdir='LR', ranksep=leafs)
g.view()
root = "0"
def _sub_plot(g, tree, inc):
global root
first_label = list(tree.keys())[0]
ts = tree[first_label]
for i in ts.keys():
if isinstance(tree[first_label][i], dict):
root = str(int(root) + 1)
g.node(root, list(tree[first_label][i].keys())[0])
g.edge(inc, root, str(i))
_sub_plot(g, tree[first_label][i], root)
else:
root = str(int(root) + 1)
g.node(root, tree[first_label][i])
g.edge(inc, root, str(i))
tree = {
"tearRate": {
"reduced": "no lenses",
"normal": {
"astigmatic": {
"yes": {
"prescript": {
"myope": "hard",
"hyper": {
"age": {
"young": "hard",
"presbyopic": "no lenses",
"pre": "no lenses"
}
}
}
},
"no": {
"age": {
"young": "soft",
"presbyopic": {
"prescript": {
"myope": "no lenses",
"hyper": "soft"
}
},
"pre": "soft"
}
}
}
}
}
}
plot_model(tree, "tree.gv")
效果如下:
# 生成树结构
def get_trees(data,
key_column='elementId',
parent_column='parentId',
child_column='children'):
"""
:param data: 数据列表
:param key_column: 主键字段,默认id
:param parent_column: 父ID字段名,父ID默认从0开始
:param child_column: 子列表字典名称
:return: 树结构
"""
data_dic = {}
for d in data:
data_dic[d.get(key_column)] = d # 以自己的权限主键为键,以新构建的字典为值,构造新的字典
data_tree_list = [] # 整个数据大列表
for d_id, d_dic in data_dic.items():
pid = d_dic.get(parent_column) # 取每一个字典中的父id
if not pid: # 父id=0,就直接加入数据大列表
data_tree_list.append(d_dic)
else: # 父id>0 就加入父id队对应的那个的节点列表
try: # 判断异常代表有子节点,增加子节点列表=[]
data_dic[pid][child_column].append(d_dic)
except KeyError:
data_dic[pid][child_column] = []
data_dic[pid][child_column].append(d_dic)
return data_tree_list
def recursion(data, l=None):
if l is None:
l = []
for i in data:
if 'children' in i:
children=i.pop('children')
l.append(i)
recursion(children,l)
else:
l.append(i)
return l
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: python字典生成树状图的实例
本文链接: https://lsjlt.com/news/119408.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0