【发布时间】: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