Python KeyError 中哪个键失败?

新手上路,请多包涵

如果我抓到 KeyError ,我怎么知道什么查找失败了?

 def poijson2xml(location_node, POI_JSON):
  try:
    man_json = POI_JSON["FastestMan"]
    woman_json = POI_JSON["FastestWoman"]
  except KeyError:
    # How can I tell what key ("FastestMan" or "FastestWoman") caused the error?
    LogErrorMessage ("POIJSON2XML", "Can't find mandatory key in JSON")

原文由 QuestionC 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
2 个回答

以当前异常为例(在本例中我使用了它 as e );然后对于 KeyError 第一个参数是引发异常的键。因此我们可以这样做:

 except KeyError as e:  # One would do it as 'KeyError, e:' in Python 2.
    cause = e.args[0]

这样,您就有了违规密钥存储在 cause 中。

扩展您的示例代码,您的日志可能如下所示:

 def poijson2xml(location_node, POI_JSON):
  try:
    man_json = POI_JSON["FastestMan"]
    woman_json = POI_JSON["FastestWoman"]
  except KeyError as e:
    LogErrorMessage ("POIJSON2XML", "Can't find mandatory key '"
    e.args[0]
    "' in JSON")

应该注意的是 e.message 在 Python 2 中有效,但在 Python 3 中无效,因此不应使用它。

原文由 anon582847382 发布,翻译遵循 CC BY-SA 4.0 许可协议

不确定您是否正在使用任何模块来帮助您 - 如果 JSON 作为字典输入,则可以使用 dict.get() 达到有用的目的。

 def POIJSON2DOM (location_node, POI_JSON):
    man_JSON = POI_JSON.get("FastestMan", 'No Data for fastest man')
    woman_JSON = POI_JSON.get("FastestWoman", 'No Data  for fastest woman')
    #work with the answers as you see fit

dict.get() 有两个参数——第一个是你想要的 key ,第二个是如果该键不存在则返回的值。

原文由 user890167 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题