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

标签 python python-3.x dictionary data-structures hierarchical-data

我需要在 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"
              }
      ]

我已经尝试过这个递归函数,并且我得到了正确的结构,但是它聚合了前三个 child 的 2 个副本,我真的不需要它。根 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:我需要以动态方式支持它,因为用户可以在数据库中添加 child 。

最佳答案

我认为问题在于您的 build 函数将节点列表作为输入,并且不会成对地对单个节点或其他一些“较小列表”类型的节点进行操作方式。因此,递归在这里并没有真正的意义。 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))

关于python - 使用 python 创建分层数据。基于结果列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395289/

相关文章:

python - 如何解释和转换 Keras 分类器的预测值?

python - Haar Training : error (-215)_img. row * _img.cols == vecSize 函数

python - 属性错误 : __exit__ with socketserver on python-3. 4.3

Python3 : writing info from a text file to a csv file

python - 如何编码python字典?

wpf - 合并字典中共享的静态资源

python - 字典列表中所有键的联合

python - 使用脚本克隆私有(private) Github 存储库

python - 正则表达式格式化没有空格的url

python - 写入文本文档时,它不会给出所有给定的密码