python 字典生成樹狀圖的實(shí)例
更新時間:2022年07月16日 17:08:02 作者:num270710
這篇文章主要介紹了python 字典生成樹狀圖的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
python字典生成樹狀圖
from graphviz import Digraph
# 獲取所有節(jié)點(diǎn)中最多子節(jié)點(diǎn)的葉節(jié)點(diǎn)
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")效果如下:

python生成樹結(jié)構(gòu)
# 生成樹結(jié)構(gòu)
def get_trees(data,
key_column='elementId',
parent_column='parentId',
child_column='children'):
"""
:param data: 數(shù)據(jù)列表
:param key_column: 主鍵字段,默認(rèn)id
:param parent_column: 父ID字段名,父ID默認(rèn)從0開始
:param child_column: 子列表字典名稱
:return: 樹結(jié)構(gòu)
"""
data_dic = {}
for d in data:
data_dic[d.get(key_column)] = d # 以自己的權(quán)限主鍵為鍵,以新構(gòu)建的字典為值,構(gòu)造新的字典
data_tree_list = [] # 整個數(shù)據(jù)大列表
for d_id, d_dic in data_dic.items():
pid = d_dic.get(parent_column) # 取每一個字典中的父id
if not pid: # 父id=0,就直接加入數(shù)據(jù)大列表
data_tree_list.append(d_dic)
else: # 父id>0 就加入父id隊(duì)對應(yīng)的那個的節(jié)點(diǎn)列表
try: # 判斷異常代表有子節(jié)點(diǎn),增加子節(jié)點(diǎn)列表=[]
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以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
利用matplotlib+numpy繪制多種繪圖的方法實(shí)例
matplotlib是Python最著名的繪圖庫,本文給大家分享了利用matplotlib+numpy繪制多種繪圖的方法實(shí)例,其中包括填充圖、散點(diǎn)圖(scatter plots)、. 條形圖(bar plots)、等高線圖(contour plots)、 點(diǎn)陣圖和3D圖,需要的朋友可以參考借鑒,下面來一起看看吧。2017-05-05
關(guān)于Python的json字符串與json模塊解讀
這篇文章主要介紹了關(guān)于Python的json字符串與json模塊解讀,JSON采用完全獨(dú)立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C,?C++,?C#,?Java,?JavaScript,?Perl,?Python等),這些特性使JSON成為理想的數(shù)據(jù)交換語言,需要的朋友可以參考下2023-07-07
Python實(shí)現(xiàn)為PDF大文件批量去除水印
在閱讀過程中如果遇到一些帶有水印的資料是比較煩心的,而市面上去水印的功能有多要收費(fèi)且很不方便,那么,如何通過Python來對這類圖片水印進(jìn)行去除呢,本文就來和大家分享一下實(shí)現(xiàn)方法吧2023-05-05
Python日志打印里logging.getLogger源碼分析詳解
在本篇文章里小編給大家整理的是一篇關(guān)于Python logging.getLogger源碼分析的相關(guān)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。2021-01-01
關(guān)于Python字符編碼與二進(jìn)制不得不說的一些事
這篇文章主要給大家介紹了關(guān)于Python字符編碼與二進(jìn)制不得不說的一些事,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Python入門教程(十一)Python中的運(yùn)算符
這篇文章主要介紹了Python入門教程(十一)Python中的運(yùn)算符,Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下2023-04-04
python使用requests+excel進(jìn)行接口自動化測試的實(shí)現(xiàn)
在當(dāng)今的互聯(lián)網(wǎng)時代中,接口自動化測試越來越成為軟件測試的重要組成部分,本文就來介紹了python使用requests+excel進(jìn)行接口自動化測試的實(shí)現(xiàn),感興趣的可以了解一下2023-11-11

