Converting tree list to hierarchy dict

前端 未结 5 1742
日久生厌
日久生厌 2021-02-06 06:39

I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.

I want to convert this list to hierarchy dict. Example of output dict:

5条回答
  •  北海茫月
    2021-02-06 07:13

    a nice recursive way to do it:

    def build_tree(elems):
      elem_with_children = {}
    
      def _build_children_sub_tree(parent):
          cur_dict = {
              'id': parent,
              # put whatever attributes here
          }  
          if parent in elem_with_children.keys():
              cur_dict["children"] = [_build_children_sub_tree(cid) for cid in elem_with_children[parent]]
          return cur_dict
    
      for item in elems:
          cid = item['id']
          pid = item['parent']
          elem_with_children.setdefault(pid, []).append(cid)
    
      res = _build_children_sub_tree(-1) # -1 is your root
      return res
    

提交回复
热议问题