# coding=utf-8
‘‘‘
通过父子key关系形成一个字典类型的列表
‘‘‘
deparetment = [{‘id‘: ‘03F50D0FE48A4C77896411D007C72A5B‘, ‘name‘: ‘2级部门‘, ‘p_id‘: ‘8F0095616A17484DAD2C17925C04B78E‘},
{‘id‘: ‘07A592FE111E4B338AC967531AB99A7E‘, ‘name‘: ‘4级部门‘, ‘p_id‘: ‘A54DF3E5EBC14254ACF65BC20C2BF4B6‘},
{‘id‘: ‘1F211E1C1D504EE0A1224F0757C67E8F‘, ‘name‘: ‘2级部门2‘, ‘p_id‘: ‘4D9190D6132441D19F9DF4DA19948AFD‘},
{‘id‘: ‘3E449618073044819C1C729A7447DE13‘, ‘name‘: ‘5级部门‘, ‘p_id‘: ‘07A592FE111E4B338AC967531AB99A7E‘},
{‘id‘: ‘4D9190D6132441D19F9DF4DA19948AFD‘, ‘name‘: ‘3333‘, ‘p_id‘: ‘-1‘},
{‘id‘: ‘8F0095616A17484DAD2C17925C04B78E‘, ‘name‘: ‘111‘, ‘p_id‘: ‘-1‘},
{‘id‘: ‘A54DF3E5EBC14254ACF65BC20C2BF4B6‘, ‘name‘: ‘3级部门‘, ‘p_id‘: ‘03F50D0FE48A4C77896411D007C72A5B‘},
{‘id‘: ‘E11306E5EABB477C9098886CF7F63731‘, ‘name‘: ‘2222‘, ‘p_id‘: ‘-1‘}]
# 获取部门树
def get_all_department_tree(dp):
top = []
# 找出顶级部门,顶级部门p_id=-1
for d in dp:
info = {}
if d[‘p_id‘] == ‘-1‘:
info["value"] = d["id"]
info["label"] = d["name"]
top.append(info)
#从每个顶级部门递归查找子部门
for c in top:
set_children(c, dp)
return top
#递归查找部门
def set_children(c, dp):
c["children"] = []
n = 0
for d in dp:
info = {}
if c["value"] == d["p_id"]:
n = n + 1
info["value"] = d["id"]
info["label"] = d["name"]
c["children"].append(info)
if n:
for cc in c["children"]:
return set_children(cc, dp) # 递归在下级继续查找
else:
c.pop(‘children‘)
print get_all_department_tree(deparetment)
原文地址:https://www.cnblogs.com/leomo/p/9851744.html