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

Python深度嵌套字典如何便捷索引?支持按路径访问的实现方案

Python嵌套字典按路径取值的实现方法

确实有多种便捷实现方案,以下是两种生产环境常用的写法:

方案1:通用工具函数(无需修改原有字典结构)

不需要改动现有字典的定义,写独立函数直接调用即可,灵活性最高:

def get_nested_value(data: dict, path: str, sep: str = '/', default=None):
    keys = path.split(sep)
    current = data
    try:
        for key in keys:
            current = current[key]
        return current
    except (KeyError, TypeError):
        # KeyError对应路径节点不存在,TypeError对应中间节点不可索引
        return default

调用示例:

x = {'a': {'b': {'c': {'d': 1}}}}
# 正常路径取值
item = get_nested_value(x, 'a/b/c/d')  # 返回1
# 路径不存在时返回自定义默认值
item2 = get_nested_value(x, 'a/b/e/f', default=0)  # 返回0

方案2:自定义Dict子类,支持直接调用get_path方法

完全贴合你示例的调用形式,继承原生dict扩展方法即可:

class PathDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 递归将所有嵌套子字典转为PathDict,保证深层也可以调用get_path
        for k, v in self.items():
            if isinstance(v, dict) and not isinstance(v, PathDict):
                self[k] = PathDict(v)

    def get_path(self, path: str, sep: str = '/', default=None):
        keys = path.split(sep)
        current = self
        try:
            for key in keys:
                current = current[key]
            return current
        except (KeyError, TypeError):
            return default

调用示例:

x = PathDict({'a': {'b': {'c': {'d': 1}}}})
item = x.get_path('a/b/c/d')  # 返回1

额外说明

  • 可根据需求自定义分隔符,比如用.作为分隔符,只需要调用时传入sep='.'即可适配不同路径写法
  • 两种方案都自带容错能力,比原生逐层索引的稳定性更强,避免路径不存在直接抛出异常中断程序
  • 如果路径中包含数字类型的key(比如列表索引、整数型字典key),可以在遍历key时增加类型转换逻辑,自动把数字格式的字符串转为int适配场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:06:01