You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:40:07