Search code examples
pythonkeyerror

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".


Solution

  • 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.