如何遍历Python字典并避免KeyError?嵌套JSON解析优化方案咨询
处理嵌套JSON可选键的优化方案
链式调用dict.get()+默认值
直接将多层get()链式调用,给上层键设置默认空字典,避免层层判断:
error_code = json.get('errors', {}).get('code') if error_code is not None and error_code != 0: this_is_bad_throw_error
当errors不存在时,json.get('errors', {})返回空字典,后续.get('code')只会返回None,无需多层嵌套if判断。
Python 3.8+:结合海象运算符简化逻辑
如果使用Python 3.8及以上版本,可通过海象运算符:=将赋值与判断合并:
if (error_code := json.get('errors', {}).get('code')) is not None and error_code != 0: this_is_bad_throw_error
自定义实现类似Ruby的dig()方法
如果习惯Ruby的dig写法,可自行实现一个纯内置的版本:
def dig(obj, *keys): for key in keys: if isinstance(obj, dict) and key in obj: obj = obj[key] else: return None return obj # 使用示例 error_code = dig(json, 'errors', 'code') if error_code is not None and error_code != 0: this_is_bad_throw_error
该函数会逐层遍历指定键,任意一层不存在则返回None,完全依赖Python内置语法,适配所有版本。
可选:外部库方案(非内置)
若运行环境允许,pydantic等数据验证库可通过定义模型自动处理缺失键与类型校验,但优先内置方法时,上述方案已足够满足需求。
内容的提问来源于stack exchange,提问作者mire3212
相关产品推荐
相关产品推荐

