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

Python如何用模式匹配在列表任意位置匹配并提取嵌套字典字段值

Python 的序列模式语法规定单条序列匹配规则内最多只能使用1个星号通配符,你尝试写的[*_, {'status': 'progress', ...}, *_]同时出现了2个星号,因此触发语法错误。

你可以遍历outer列表的每个元素,对单个元素做模式匹配实现需求,全程不需要手动编写键存在性校验逻辑,实现代码如下:

my_dict = {
    "outer": [
        {"status": "to do", "desc": [{"msg": "foo"}]},
        {"status": "progress", "desc": [{"msg": "bar"}]},
        {"status": "done", "desc": [{"msg": "baz"}]},
    ]
}

for item in my_dict.get("outer", []):
    match item:
        case {"status": "progress", "desc": [{"msg": x}]}:
            print(x)

运行上述代码会直接输出bar,符合预期。

该写法自带容错能力:

  • 外层字典不存在outer键时,get方法返回空列表,不会抛出异常
  • 列表元素缺少status/desc键、status值不为progress、desc结构不符合预期时,都会自动匹配失败跳过,无需手动写in判断逻辑。

如果需要提取所有符合条件的msg,只需要把匹配到的x存到列表中即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:36:03