【问题标题】:Handle multiple errors in nested dictionary/lists处理嵌套字典/列表中的多个错误
【发布时间】:2021-10-15 17:07:37
【问题描述】:

我想循环使用大量嵌套列表和字典的 json 文件(json string1、2、3 等)。所以我需要同时处理 KeyErrors 和 IndexErrors 以防缺少值。进入我的循环的 json 结构示例:

Json 字符串 1: 'questions': {'39860004': [{'15920003': 2.6, '25860009': 1.6, '11990005': [{'name': 'croton'}], '48090004': [{'name': 'Mark'}], '11980002': 0.6, '40310003': [{'name': 'croton_macrostachyus'}], '40300005': 5.3, '5900005': 0.29, '21860001': 0.45,'50110005':0.7,'53213':{'lat':1.198,'long':32.767,'elev':无,'code':无},'54040005':2.5,'2345677':[{ '名称': '巴豆'}]}

所以对于每个 json,我需要遍历每个嵌套项并提取值。

为此,我使用了一个 for 循环:

for x in json string 1['questions']['39860004']:
   value 1 = x['15920003']
   value 2 = x['25860009']
   etc.

现在,我需要同时处理 KeyErrors(用于缺少字典项)和 IndexErrors(用于缺少列表)。我怎样才能最好地使代码健壮?问题是,当在 json 中找不到某个值时,我仍然需要留在循环中才能找到其他值。

我试过了:

for x in json string 1['questions']['39860004']:
   Try:
     value 1 = x['15920003']
   except IndexError:
     value 1 = ''
   else KeyError:
     value 1 = ''
   Etc....

但是,除了我在这种语法上遇到错误之外,这种方法似乎并不一致。我还可以为每个分别处理 Key- 和 IndexErrors 的项目创建一个新的“for循环”,但这对我来说似乎并不优雅。有什么建议可以有效(和优雅)地解决这个问题吗?

【问题讨论】:

  • else 也应该是 except。您可以同时捕获这两种情况:except (IndexError, KeyError):
  • 以前从未有过如此快速的响应(我仍在编辑我的问题,而您已经给出了答案......)并且有一个很好的解决方案!非常感谢。这行得通。有时解决方案很简单。

标签: python json loops error-handling nested


【解决方案1】:

您可以使用except (KeyError, Indexerror) as e:一次排除多个错误

如果您想排除错误并对错误做出不同的反应,您可以将“try and except”嵌套在另一个错误中。

try:
     try:
         <code>
     except error 1:
         <error handling 1>
except error 2:
     <error handling 2>
   

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多