【问题标题】:handling exception KeyError - Python处理异常 KeyError - Python
【发布时间】:2015-07-14 21:41:22
【问题描述】:

我在以下代码中得到一个“KeyError”来表示不存在的key

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()

这是错误:

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

如何检查该键是否具有值,然后将其分配给"num1", "num2"

【问题讨论】:

  • 你能编辑你的代码吗?引号很乱。另外,知道错误发生在哪一行会很有帮助。
  • 另外,dict.get('key', defaultValue) 非常有用。

标签: python keyerror


【解决方案1】:

类似的东西:

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

由于执行是贪心的,如果条件为False,Python 将不会评估str(ch_id[x[2]]['num1']),因此不会出现错误。它只会跳过丢失的键。如果你不知道这个语法,你可以阅读here

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2020-12-23
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多