Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want dict2 to look something like:

{0: [results1], [results2], 1: [results3], [results4]}

Appreciate any help.

>Solution :

You have to create an empty dictionary in dict2[item] so you can assign to its keys.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading