根据父子信息 还原成json树
需求
有一组数据 ([1,2], [2, 3], [1, 5], [5, 6]), 列表里的数据分别为父节点,子节点。将这组数据还原成树状json数据。
代码
定义一个Node对象
import json
from collections import defaultdict
class Node:
def __init__(self, key, info):
self.key = key
self.info = info
self.children = []
def to_dict(self):
result = dict()
result["key"] = self.key
for _k, _v in self.info.items():
result[_k] = _v
result["children"] = [x.to_dict() for x in self.children]
return result
class TreeProcessor:
def __init__(self, pair: list, info: dict, d_type="json"):
"""
:param pair: [(0, 1), (0, 2)...] 父子关系对
:param info: {0 : {"name": xxx}} 每个节点的详细信息
:param d_type: 返回类型 json dict
"""
self._pair = pair
self._info = info
self.d_type = d_type
self.root_id, self._pair_map, self._ids = self._process_data()
def _process_data(self):
"""
将[(0, 1), (0, 2)...] 父子关系对
变为 {father: [child, child]}
:return:
"""
pair_map = defaultdict(list)
ids = set()
fathers = set()
children = set()
for f, s in self._pair:
ids.add(f)
ids.add(s)
fathers.add(f)
children.add(s)
pair_map[f].append(s)
root_id = fathers - children
root_id = list(root_id)[0] if root_id else None
return root_id, pair_map, ids
def _create_nodes(self):
return {x: Node(x, self._info.get(x, {})) for x in self._ids}
@property
def tree(self):
node_map = self._create_nodes()
for k, v in self._pair_map.items():
node_map[k].children = [node_map[i] for i in v]
root_node: Node = node_map.get(self.root_id)
tree_res = json.dumps(root_node.to_dict()) if self.d_type == 'json' else root_node.to_dict()
return tree_res
结果
infos = {0: {"name": "zero", "alias": "ling"},
1: {"name": "one", "alias": "yi"},
2: {"name": "two", "alias": "er"},
3: {"name": "three", "alias": "san"},
4: {"name": "four", "alias": "si"},
5: {"name": "five", "alias": "wu"},
6: {"name": "six", "alias": "liu"},
7: {"name": "seven", "alias": "qi"}}
relation = [(0, 1),
(0, 2),
(0, 3),
(2, 4),
(2, 5),
(5, 6),
(5, 7)]
tp = TreeProcessor(relation, infos)
tree_dict = tp.tree
print(tree_dict)
tree json
{
"key": 0,
"name": "zero",
"alias": "ling",
"children": [
{
"key": 1,
"name": "one",
"alias": "yi",
"children": []
},
{
"key": 2,
"name": "two",
"alias": "er",
"children": [
{
"key": 4,
"name": "four",
"alias": "si",
"children": []
},
{
"key": 5,
"name": "five",
"alias": "wu",
"children": [
{
"key": 6,
"name": "six",
"alias": "liu",
"children": []
},
{
"key": 7,
"name": "seven",
"alias": "qi",
"children": []
}
]
}
]
},
{
"key": 3,
"name": "three",
"alias": "san",
"children": []
}
]
}
|