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

Python3中如何通过多键路径访问多维嵌套字典中的对应值

实现方案

首先给出基础版本实现,适配你给出的固定全局字典a的需求:

a = {
    'b': {
        'c': {
            'd': 1
        }
    }
}

def get_value(path):
    # 统一把路径转换为键列表
    key_list = path.split('.') if isinstance(path, str) else path
    current_node = a
    for key in key_list:
        current_node = current_node[key]
    return current_node

调用测试

  • 点分隔字符串传参:get_value('b.c.d') 返回结果为 1
  • 列表形式传参:get_value(['b','c','d']) 返回结果为 1

扩展优化版本(支持任意字典+异常兼容)

如果需要适配不同的多维字典,同时避免路径不存在时抛出异常,可以调整为如下实现:

def get_value(data, path, default=None):
    """
    从多维字典中按路径取值
    :param data: 目标多维字典
    :param path: 点分隔字符串/键列表形式的路径
    :param default: 路径不存在时返回的默认值
    """
    key_list = path.split('.') if isinstance(path, str) else path
    current_node = data
    try:
        for key in key_list:
            current_node = current_node[key]
        return current_node
    except (KeyError, IndexError, TypeError):
        # 捕获键不存在、列表索引越界、中间节点不可索引的异常
        return default

扩展版本调用示例

# 取存在的路径
print(get_value(a, 'b.c.d')) # 输出 1
# 取不存在的路径,返回默认值
print(get_value(a, 'b.c.e', default=0)) # 输出 0

内容的提问来源于stack exchange,提问作者e-info128

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:15:02