如何构建从子级到父级的字典?

时间:2015-11-03 10:24:36

标签: python sql dictionary

所以我正在使用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看起来像一个典型的嵌套字典(可能比这个例子中的级别更多: 祖父母{Parent1:[Child1,Child2],Parent2:Child3}

1 个答案:

答案 0 :(得分:0)

以下是我如何用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)