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

如何用斜杠分隔字符串访问YAML加载的嵌套字典元素?

实现嵌套字典的路径式访问

自定义斜杠路径解析实现

你可以通过手动解析斜杠分隔的路径字符串,实现类似get_by_full_path的功能。以下是一个简单的实现函数:

import yaml

def get_by_full_path(data, path):
    # 移除路径开头的斜杠并分割成各个层级
    path_parts = path.lstrip('/').split('/')
    current_node = data
    for part in path_parts:
        if isinstance(current_node, dict) and part in current_node:
            current_node = current_node[part]
        else:
            # 可根据需求修改:返回None或抛出异常
            raise KeyError(f"路径层级 '{part}' 不存在于当前节点")
    return current_node

# 使用示例
data = yaml.load(open(yamlfile), Loader=yaml.FullLoader)
target_value = get_by_full_path(data, '/foo/bar/baz')
# target_value 即为 'qux'

如果希望字典实例能直接调用该方法,也可以通过继承dict类来扩展,但一般推荐使用独立函数以避免修改内置类型的行为。


基于jsonpath_ng的实现方案

借助jsonpath_ng库可以更灵活地查询嵌套结构,无需自己处理路径解析:

  1. 先安装依赖库:
pip install jsonpath-ng
  1. 使用示例代码:
import yaml
from jsonpath_ng import parse

data = yaml.load(open(yamlfile), Loader=yaml.FullLoader)
# 使用点分隔的jsonpath语法定位目标元素
result = parse('foo.bar.baz').find(data)[0].value
print(result)  # 输出 'qux'

该库还支持更复杂的查询逻辑(如数组索引、条件筛选等),适合处理复杂的嵌套数据结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:29:55