Python 如何从孩子到家长建立字典?

Python 如何从孩子到家长建立字典?,python,sql,dictionary,Python,Sql,Dictionary,因此,我正在使用python和sql。我有一些数据结构如下: 祖父母: 母公司 孩子 当前代码,当给定时,子对象将获取包含父对象和祖父母的列表(它使用父对象ID获取祖父母) 现在我需要以分层的方式获取这些信息,所以我把它看作是一个字典,但我找不到添加新的“超级键”的方法,在每次迭代中,它会替换其他键 (注意:它可以有3个以上的级别,但我无法事先知道有多少个级别的家长) 编辑:这是当前代码: def Parenting(ChildID) cursor.execute("SE

因此,我正在使用python和sql。我有一些数据结构如下:

  • 祖父母:

    • 母公司

      • 孩子
当前代码,当给定时,子对象将获取包含父对象和祖父母的列表(它使用父对象ID获取祖父母)

现在我需要以分层的方式获取这些信息,所以我把它看作是一个字典,但我找不到添加新的“超级键”的方法,在每次迭代中,它会替换其他键

(注意:它可以有3个以上的级别,但我无法事先知道有多少个级别的家长)

编辑:这是当前代码:

def Parenting(ChildID)  
    cursor.execute("SELECT * FROM Parent_Child where ChildId ="+ChildID)
    Pathway_Du_ID = cursor.fetchall()
    Pathway_IDs = []
    done = []
    for Path in Pathway_Du_ID:
            Pathway_IDs.append(Path[0])
    for ele in Pathway_IDs:
            ele = str(ele)
            if ele not in done:
                    done.append(ele)
                    cursor.execute("SELECT * FROM Parent_Child where ChildId ="+ele)
                    Du = cursor.fetchall()
                    for l in Du:
                            Pathway_IDs.append(l[0])

    return Pathway_IDs
最终的dict看起来像一个典型的嵌套dict(可能比本例中的级别更多:
祖父母{Parent1:[Child1,Child2],Parent2:Child3}

下面是我可以如何使用sqlite来完成的。在
Parenting()
中,我建立了一个按ID索引的并行数据结构,以便在构建树时保存各个关系

import sqlite3
import pprint

def init_db(conn):
    with conn:
        conn.execute("""create table People (
                            Id integer primary key ASC,
                            Name)""")
        conn.execute("""insert into People values
                            ( 1, "Homer"),
                            ( 2, "Bart"),
                            ( 3, "Lisa"),
                            ( 4, "Maggie"),
                            ( 5, "Abe" )""")

        conn.execute("""create table Parent_Child (
                            ChildId INTEGER UNIQUE,
                            ParentId INTEGER )""")
        conn.execute("""insert into Parent_Child values
                            (1, 5),
                            (3, 1), (4, 1), (2, 1)""")

def Parenting(conn):
    global root
    population_by_id = {}
    sql =  "select ParentId, ChildId from Parent_Child"
    for parent_id, child_id in conn.execute(sql):
        parent = population_by_id.setdefault(parent_id, {})
        child = population_by_id.setdefault(child_id, {})
        parent[child_id] = child
    sql = """select ParentID from Parent_Child
              where ParentID not in (select ChildID from Parent_Child)"""
    eldest = next(conn.execute(sql))[0]
    root = { eldest : population_by_id[eldest] }


if __name__=="__main__":
    conn = sqlite3.connect(':memory:')
    init_db(conn)
    Parenting(conn)
    pprint.pprint(root)

什么是祖父母的父母id?我真的不明白你的问题。所以所有id(父母、祖父母和孩子)看起来都一样,这就是为什么我把它“倒过来”的原因对于相同的迭代,我的问题是,孩子如何知道谁是父母。另外,给我你的代码注意代码中的sql注入攻击漏洞。不要像那样构建sql字符串。文档教你如何在没有漏洞的情况下进行。你能举个例子说明你的dict是什么样子的吗?