handling exception KeyError - Python -


i getting "keyerror" non-existing key in following code:

c.execute("select * table1 col1 = 'test'") res = c.fetchall() sum = 0 x in res:     print "res: ",res      d = {"num1"     : [  str(testval[x[2]]['num1']) x in res ],          "num2"     : [ str(testval[x[2]]['num2']) x in res ],          }     conn.close() 

this error:

    "num1": [  str(testval[x[2]]['num1']) x in res ], keyerror: u'13' 

how can check see if key has value assign "num1", "num2".

something that:

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

since execution greedy, python not evaluate str(ch_id[x[2]]['num1']) if condition false, no errors. skip missing keys. if don't know syntax, can read here.


Comments