简体   繁体   中英

handling exception KeyError - Python

I am getting a " KeyError " for a non-existing key in following code:

c.execute("SELECT * FROM table1 where col1 = 'test'")
res = c.fetchall()
sum = 0
for x in res:
    print "res: ",res

    d = {"num1"     : [  str(testVal[x[2]]['num1']) for x in res ],
         "num2"     : [ str(testVal[x[2]]['num2']) for x in res ],
         }
    conn.close()

This is the error:

    "num1": [  str(testVal[x[2]]['num1']) for x in res ],
KeyError: u'13'

How can I check to see if that key has value then assign it to "num1", "num2" .

Something like that:

"num1": [ str(ch_id[x[2]]['num1']) for x in res if x[2] in ch_id]

Since the execution is greedy, Python will not evaluate str(ch_id[x[2]]['num1']) if the condition is False , so you get no errors. It will just skip the missing keys. If you don't know this syntax, you can read here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM