Converting tree list to hierarchy dict

前端 未结 5 1759
日久生厌
日久生厌 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:37

    Something simple like this might work:

    def build_tree(category_data):
      top_level_map = {}
      cat_map = {}
      for cat_name, parent, depth in cat_data:
        cat_map.setdefault(parent, {})
        cat_map.setdefault(cat_name, {})
        cat_map[parent][cat_name] = cat_map[cat_name]
        if depth == 0:
          top_level_map[cat_name] = cat_map[cat_name]
    
      return top_level_map
    

提交回复
热议问题