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

Python中如何遍历键列表获取嵌套字典层级值,无效时返回False且不使用eval

嵌套字典按序列键取值的实现

场景说明

你需要处理的输入定义如下:

  • 顺序访问的键列表示例:keys = ["key1", "key2", "key3"]
  • 待访问的嵌套字典结构示例:
nested_dict = {
    "key1": {
        "key2": {
            "key3": "Value I want to receive"
        }
    }
}

核心要求

  • 按键列表的先后顺序逐层访问字典,最终返回对应层级的值,等效于手动执行nested_dict["key1"]["key2"]["key3"]的效果
  • 访问链路任意一层失效(如对应键不存在、当前层级不是可索引的字典结构),直接返回False
  • 禁止使用eval()这类动态执行代码的方案实现

可落地的实现方案

方案1:基于try-except异常捕获实现

这是符合Python编码习惯的简洁实现方式,顺着层级逐次取值,碰到访问错误时直接返回失效标识:

def get_nested_value(source, key_chain):
    current = source
    for key in key_chain:
        try:
            current = current[key]
        except (KeyError, TypeError):
            # KeyError:当前字典层不存在对应键
            # TypeError:当前值不是可索引的字典/映射结构,无法继续取键
            return False
    return current

调用测试示例:

# 正常链路测试
keys = ["key1", "key2", "key3"]
nested_dict = {
    "key1": {
        "key2": {
            "key3": "Value I want to receive"
        }
    }
}
print(get_nested_value(nested_dict, keys))  # 输出:Value I want to receive

# 失效链路测试1:某层缺失对应键
bad_dict1 = {"key1": {"other_key": "无key2层级"}}
print(get_nested_value(bad_dict1, keys))  # 输出:False

# 失效链路测试2:中间层不是字典结构
bad_dict2 = {"key1": "字符串类型,无法继续向下取键"}
print(get_nested_value(bad_dict2, keys))  # 输出:False

注意:这里仅捕获KeyError和TypeError两类和取值相关的异常,不会误吞其他非预期的程序错误,安全性更高。

方案2:无异常捕获的显式判断实现

如果偏好先判断再操作的编码逻辑,可以逐次校验当前层级的合法性后再取值:

def get_nested_value_strict(source, key_chain):
    current = source
    for key in key_chain:
        # 同时校验当前层是字典结构、且目标键存在
        if not isinstance(current, dict) or key not in current:
            return False
        current = current[key]
    return current

小提示:如果你的业务场景中,嵌套字典存储的合法值本身就可能是布尔值False,建议将链路失效的返回值替换为None或自定义的标记对象,避免和合法值产生混淆。


内容的提问来源于stack exchange,提问作者newbypyth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 16:06:02