import pprint
department_list = [
{'id': 1, 'label': '总部', 'parent_id': None, "children": []},
{'id': 2, 'label': '分部', 'parent_id': 1, "children": []},
{'id': 3, 'label': '部门一', 'parent_id': 2, "children": []},
{'id': 4, 'label': '部门二', 'parent_id': 2, "children": []},
]
department_dict = {}
for department in department_list:
department_dict[department["id"]] = department
pprint.pprint(department_dict)
"""
{1: {'children': [], 'id': 1, 'label': '总部', 'parent_id': None},
2: {'children': [], 'id': 2, 'label': '分部', 'parent_id': 1},
3: {'children': [], 'id': 3, 'label': '部门一', 'parent_id': 2},
4: {'children': [], 'id': 4, 'label': '部门二', 'parent_id': 2}}
"""
department_data = []
for department in department_list:
pid = department["parent_id"]
if pid:
department_dict["label"] = department['label']
department_dict[pid]["children"].append(department)
else:
department_data.append(department)
pprint.pprint(department_data)
"""
[{'children': [{'children': [{'children': [],
'id': 3,
'label': '部门一',
'parent_id': 2},
{'children': [],
'id': 4,
'label': '部门二',
'parent_id': 2}],
'id': 2,
'label': '分部',
'parent_id': 1}],
'id': 1,
'label': '总部',
'parent_id': None}]
"""