'Python: Assigning query results to nested dictionary keys
In a flask project, I am looping through two lists to execute queries. Items from each list are variables in the SQL statements. I want the results of each query assigned to a key in the results dict:
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 looks good, but the above gives me KeyError: 0 on dict2.
If I change the last bit to dict2[criterion] = bar
Then dict2 only contains results from the query from list1[1] - like so:
{[result3], [result4]}
I want dict2 to look something like:
{0: [results1], [results2], 1: [results3], [results4]}
Appreciate any help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
