【问题标题】:How do I build a dictionary from child to parent?如何建立从孩子到父母的字典?
【发布时间】:2016-02-03 11:03:14
【问题描述】:

所以我正在使用 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

最终的字典看起来像一个典型的嵌套字典(可能比这个例子有更多的层次: 祖父母 { Parent1: [Child1, Child2], Parent2: Child3}

【问题讨论】:

  • 祖父母的父母ID是什么?
  • 我真的不明白你的问题。所以所有 ID(父母、祖父母和孩子)看起来都一样,这就是为什么我用相同的迭代“颠倒”构建它
  • 我的问题是,孩子怎么知道谁是父母。另外,给我你的代码
  • 注意代码中的 sql 注入攻击漏洞。不要像那样构建你的 sql 字符串。文档教你如何做到没有漏洞。
  • 您能举个例子,您的 dict 会是什么样子吗?

标签: python sql dictionary


【解决方案1】:

以下是我可以使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多