【问题标题】:Have a nested List in a Python Dictionary在 Python 字典中有一个嵌套列表
【发布时间】:2013-03-26 07:06:01
【问题描述】:

我有一个如下的数据库表。数据采用树的形式,带有

            CREATE  TABLE IF NOT EXISTS DOMAIN_HIERARCHY (
                COMPONENT_ID        INT             NOT NULL ,
                LEVEL               INT             NOT NULL ,
                COMPONENT_NAME      VARCHAR(127)    NOT NULL ,
                PARENT              INT             NOT NULL ,
                PRIMARY KEY ( COMPONENT_ID ) 
                );

以下数据在表格中

                (1,1,'A',0)
                (2,2,'AA',1)
                (3,2,'AB',1)
                (4,3,'AAA',2)
                (5,3,'AAB',2)
                (6,3,'ABA',3)
                (7,3,'ABB',3)

我必须检索数据并存储在 python 字典中

在下面的代码中

                conx = sqlite3.connect( 'nameofdatabase.db' )
                curs = conx.cursor()
                curs.execute( 'SELECT COMPONENT_ID, LEVEL, COMPONENT_NAME, PARENT FROM DOMAIN_HIERARCHY' )
                rows = curs.fetchall()                    
                hrcy = {}                 
                for row in rows:
                    entry = ( row[2], {} )
                    cmap[row[0]] = entry
                    if row[1] == 1:
                        hrcy = {entry[0]: entry[1]}
                        hrcy['status'] = 0
                for row in rows:
                    item = cmap[row[0]]
                    parent = cmap.get( row[3], None )
                    if parent:
                        parent[1][row[2]] = item[1]
                        parent[1]['status'] = 0
                print json.dumps( hrcy, indent = 4 )

输出是这样的

                {
                    "status": 0, 
                    "A": {
                        "status": 0, 
                        "AA": {
                            "status": 0, 
                            "AAA": {}, 
                            "AAB": {}
                        }, 
                        "AB": {
                            "status": 0, 
                            "ABA": {}, 
                            "ABB": {}
                        }
                    }
                }

我想要这样的输出

                {
                    "component": "A",
                    "status": 0,
                    "children": [
                        {
                            "component": "AA",
                            "status": 0,
                            "children": [
                                {
                                    "component": "AAA",
                                    "status": 0,
                                    "children": []
                                },
                                {
                                    "component": "AAB",
                                    "status": 0,
                                    "children": []
                                }
                            ]
                        },
                        {
                            "component": "AB",
                            "status": 0,
                            "children": [
                                {
                                    "component": "ABA",
                                    "status": 0,
                                    "children": []
                                },
                                {
                                    "component": "ABB",
                                    "status": 0,
                                    "children": []
                                }
                            ]
                        }
                    ]
                }

谁能告诉我应该做些什么改变?

【问题讨论】:

    标签: python sql json


    【解决方案1】:

    只需构造你想要的字典,而不是其他东西:

    for row in rows:
        entry = {"component": row[2], 
                 "children": [], 
                 "status": 0}
        cmap[row[0]] = entry
        if row[1] == 1:
            hrcy = entry
    for row in rows:
        item = cmap[row[0]]
        parent = cmap.get( row[3], None )
        if parent:
            parent["children"].append(item)
    

    【讨论】:

    • 不敢相信这个简单的小代码解决了我的“无法解决”的问题,非常感谢 Janne Karela
    【解决方案2】:

    我会选择这样的:

    import pprint
    
    class Node(dict):
        def __init__(self, *args):
            dict.__init__(self)
            self['id'] = args[0]
            self['group'] = args[1]
            self['component'] = args[2]
            self['parent'] = args[3]
            self['status'] = 0
            self['children'] = []
    
        def add_node(self, node):
            for child in self['children']:
                if child.is_parent(node):
                    child.add_node(node)
                    break
            else:
                self['children'].append(node)
    
        def is_parent(self, node):
            return node['component'].startswith(self['component'])
    
    class RootNode(Node):
        def __init__(self):
            Node.__init__(self, *[0, 0, "Root", -1])
    
        def is_parent(self, node):
            return True
    
    def make_tree(nodes):
        root = RootNode()
        for data in nodes:
            node = Node(*data)
            root.add_node(node)
        return root
    
    nodes =  [
            (1, 1, 'A', 0),
            (2, 2, 'AA', 1),
            (3, 2, 'AB', 1),
            (4, 3, 'AAA', 2),
            (5, 3, 'AAB', 2),
            (6, 3, 'ABA', 3),
            (7, 3, 'ABB', 3),
          ]
    
    if __name__ == "__main__":
        tree = make_tree(nodes)
        pprint.pprint(tree['children'][0])
    

    外出

    {'children': [{'children': [{'children': [],
                                 'component': 'AAA',
                                 'group': 3,
                                 'id': 4,
                                 'parent': 2,
                                 'status': 0},
                                {'children': [],
                                 'component': 'AAB',
                                 'group': 3,
                                 'id': 5,
                                 'parent': 2,
                                 'status': 0}],
                   'component': 'AA',
                   'group': 2,
                   'id': 2,
                   'parent': 1,
                   'status': 0},
                  {'children': [{'children': [],
                                 'component': 'ABA',
                                 'group': 3,
                                 'id': 6,
                                 'parent': 3,
                                 'status': 0},
                                {'children': [],
                                 'component': 'ABB',
                                 'group': 3,
                                 'id': 7,
                                 'parent': 3,
                                 'status': 0}],
                   'component': 'AB',
                   'group': 2,
                   'id': 3,
                   'parent': 1,
                   'status': 0}],
     'component': 'A',
     'group': 1,
     'id': 1,
     'parent': 0,
     'status': 0}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2018-11-25
      相关资源
      最近更新 更多