Python: 将查询结果分配给嵌套的字典键
Python: Assigning query results to nested dictionary keys
在一个 flask 项目中,我循环遍历两个列表来执行查询。每个列表中的项目都是 SQL 语句中的变量。我希望将每个查询的结果分配给结果字典中的一个键:
dict1 = {}
dict2 = {}
list1 = [0,1]
list2 = ['criteria1', 'criteria2', 'criteria3']
for item in list1:
cur.execute(query_one(item))
foo = cur.fetchall()
dict1[item] = foo
for criterion in list2:
cur.execute(query_two(item, criterion)):
bar = cur.fetchall()
dict2[item][criterion] = bar
dict1 看起来不错,但上面给出了 KeyError: 0 on dict2。
如果我将最后一位更改为 dict2[criterion] = bar
然后 dict2
只包含来自 list1[1]
的查询结果 - 像这样:
{[result3], [result4]}
我希望 dict2
看起来像:
{0: [results1], [results2], 1: [results3], [results4]}
感谢任何帮助。
您必须在 dict2[item]
中创建一个空字典,以便您可以分配给它的键。
dict1 = {}
dict2 = {}
list1 = [0,1]
list2 = ['criteria1', 'criteria2', 'criteria3']
for item in list1:
cur.execute(query_one(item))
foo = cur.fetchall()
dict1[item] = foo
dict2[item] = {}
for criterion in list2:
cur.execute(query_two(item, criterion)):
bar = cur.fetchall()
dict2[item][criterion] = bar
在一个 flask 项目中,我循环遍历两个列表来执行查询。每个列表中的项目都是 SQL 语句中的变量。我希望将每个查询的结果分配给结果字典中的一个键:
dict1 = {}
dict2 = {}
list1 = [0,1]
list2 = ['criteria1', 'criteria2', 'criteria3']
for item in list1:
cur.execute(query_one(item))
foo = cur.fetchall()
dict1[item] = foo
for criterion in list2:
cur.execute(query_two(item, criterion)):
bar = cur.fetchall()
dict2[item][criterion] = bar
dict1 看起来不错,但上面给出了 KeyError: 0 on dict2。
如果我将最后一位更改为 dict2[criterion] = bar
然后 dict2
只包含来自 list1[1]
的查询结果 - 像这样:
{[result3], [result4]}
我希望 dict2
看起来像:
{0: [results1], [results2], 1: [results3], [results4]}
感谢任何帮助。
您必须在 dict2[item]
中创建一个空字典,以便您可以分配给它的键。
dict1 = {}
dict2 = {}
list1 = [0,1]
list2 = ['criteria1', 'criteria2', 'criteria3']
for item in list1:
cur.execute(query_one(item))
foo = cur.fetchall()
dict1[item] = foo
dict2[item] = {}
for criterion in list2:
cur.execute(query_two(item, criterion)):
bar = cur.fetchall()
dict2[item][criterion] = bar