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

Python如何根据路径查找嵌套字典列表中的目标字典值

问题原因

Python原生字典相等判断为逐字段完全匹配,不支持*作为通配符省略字段匹配,你之前写的带*的target字典写法不符合Python语法,无法运行。针对多层嵌套的类文件系统结构,采用逐层遍历的方式实现路径查找逻辑最稳定,支持任意深度的嵌套目录查找。

实现逻辑
  • 预处理输入路径:拆分斜杠得到每一级路径段,自动过滤空段,兼容连续斜杠、根路径等边界场景
  • 从顶层文件系统列表开始逐段匹配:匹配时仅校验条目的type、name、ext三个固定属性,不需要匹配contents字段,从根源上避免需要通配符的问题
  • 若当前匹配到的条目为目录且仍有未匹配的路径段,进入该目录的contents列表进入下一层查找;若所有路径段匹配完成,直接返回当前找到的条目
  • 任意层级找不到匹配项、或路径中间段为文件无法继续深入时,返回None标识路径不存在
完整实现代码
filesystem = [
    {
        "type":"dir",
        "name":"examples",
        "ext":"",
        "contents":[
            {
                "type":"file",
                "name":"text_document",
                "ext":"txt",
                "contents":"This is a text document.\nIt has 2 lines!"
            }
        ]
    },
    {
        "type":"file",
        "name":"helloworld",
        "ext":"py",
        "contents":"print(\"Hello world\")"
    }
]

def find_path(fs_root, input_path):
    # 拆分路径段,过滤空值
    path_parts = [part for part in input_path.split("/") if part]
    # 传入根路径时返回包装后的根目录结构
    if not path_parts:
        return {"type": "dir", "name": "root", "ext": "", "contents": fs_root}
    
    current_level = fs_root
    for idx, part in enumerate(path_parts):
        matched_item = None
        # 遍历当前层级所有条目查找匹配项
        for item in current_level:
            # 匹配规则:目录名直接匹配,文件名匹配「名称.扩展名」格式
            if item["type"] == "dir" and item["name"] == part and item["ext"] == "":
                matched_item = item
                break
            if item["type"] == "file" and f"{item['name']}.{item['ext']}" == part:
                matched_item = item
                break
        
        if not matched_item:
            return None  # 路径不存在
        
        # 不是最后一级路径时,必须匹配到目录才能进入下一层
        if idx != len(path_parts) - 1:
            if matched_item["type"] != "dir":
                return None
            current_level = matched_item["contents"]
    
    return matched_item
调用示例
# 查找/examples目录
dir_res = find_path(filesystem, "/examples")
print(dir_res["type"]) # 输出 dir

# 查找嵌套的文本文件
file_res = find_path(filesystem, "/examples/text_document.txt")
print(file_res["contents"]) # 输出文本文件内容

# 查找根目录下的py文件
py_res = find_path(filesystem, "/helloworld.py")
print(py_res["contents"]) # 输出 print("Hello world")

# 查找不存在的路径
none_res = find_path(filesystem, "/test/not_exist")
print(none_res) # 输出 None

你可以根据自己的路径格式调整匹配规则,比如如果不需要写扩展名就能查找文件,只需要修改文件条目的判断逻辑,直接匹配name字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:39:17