使用 python 创建分层数据。基于结果列表

Create a hierarchichal data with python. based on a list of results

我需要在 python 中转换分层嵌套字典中的数据列表。一个结构体(父亲-child).

这是我的数据。

list_data = [
       {
           "id": 2,
           "father_id": 0,
           "desc": "Oficial de Negocios Senior",
           "name": "PEDRO MARTIN SOTO ROSALES"
       },
       {
           "id": 4,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Adriana Paredez"
       },
       {
           "id": 5,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Hugo Miranda"
       },
       {
           "id": 3,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Mario Azcona"
       },
           {
                  "id": 6,
                  "father_id": 3,
                  "desc": "vendedor",
                  "name": "Diana Diaz"
              }
      ]

我已经尝试过这个递归函数,并且我得到了正确的结构,但是它聚合了前三个 children 的 2 个副本,我真的不需要它。 root father 是 father_id = 0

的元素
def build(loc_key):

    children = {row['id']: {'name': row['name'], 'desc': row['desc'],
                                'child':[]} for row in list_data if row['father_id'] == loc_key}

    data = {}

    for key, value in children.items():
        data[key] = value
        for item in list_data:
            if item['father_id'] == key:
                data[key]['child'].append(build(key))
    return data

print(build(0))

这基本上就是我需要得到的

data = {
       2: {'desc': 'Oficial de Negocios Senior',
          'name': 'PEDRO MARTIN SOTO ROSALES', 
          'child': 
              [
              {3: {'desc': 'Ejecutivo comercial', 
                  'name': 'Mario Azcona', 
                  'child': [
                            {6: {'desc': 'vendedor', 
                                'name': 'Diana Diaz', 
                                 'child': []}}]}, 
              4: {'desc': 'Ejecutivo comercial', 
                 'name': 'Adriana Paredez', 
                 'child': []}, 
              5: {'desc': 'Ejecutivo comercial', 
                 'name': 'Hugo Miranda', 
                 'child': []}

PD:我需要以动态方式支持它,因为用户可以在数据库上添加 children。

我认为问题在于您的 build 函数将节点列表作为输入,而不是对单个节点成对操作或以其他 "smaller list" 排序方法。因此,递归在这里并没有真正的意义。 OTOH,一旦您构建了树(顺便说一下,您正在尝试构建树),那么递归将对解析结果结构非常有帮助。不过对建树的帮助不大。

这是构建树的一种方法。它是 O(n) 计算时间和内存,但在操作中确实存储了多个列表副本,因此可能会有一些优化。

import pprint

list_data = [
       {
           "id": 2,
           "father_id": 0,
           "desc": "Oficial de Negocios Senior",
           "name": "PEDRO MARTIN SOTO ROSALES"
       },
       {
           "id": 4,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Adriana Paredez"
       },
       {
           "id": 5,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Hugo Miranda"
       },
       {
           "id": 3,
           "father_id": 2,
           "desc": "Ejecutivo comercial",
           "name": "Mario Azcona"
       },
       {
           "id": 6,
           "father_id": 3,
           "desc": "vendedor",
           "name": "Diana Diaz"
       }
]

def tree_structure(list_data):
    #build the requisite data structure in a "flat" way... you can initialize this "as you go" in the loop below if more optimization is needed.
    data = {row["id"]: {"desc": row["desc"], "name": row["name"], "child": {}} for row in list_data}
    root_id = None
    for row in list_data:
        if row["father_id"] != 0:
            data[row["father_id"]]["child"][row["id"]] = data[row["id"]] #note that this stores only a reference to the child dictionary, so it is O(1) memory
        else:
            root_id = row["id"] #we need this later
    return {root_id: data[root_id]}

pprint.pprint(tree_structure(list_data))