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

如何从嵌套于列表的字典中获取符合条件的指定键对应值

从列表嵌套字典中获取特定键的对应值

场景示例

现有包含学生信息的列表,每个元素是存储学生详情的字典:

students = [
    {"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
    {"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
    {"name": "Draco", "house": "Slytherin", "patronus": None}
]

问题描述

尝试用以下代码筛选patronus为"Stag"的内容:

next(item for item in students if item["patronus"] == "Stag")

实际返回的是整个匹配的字典对象:{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},但期望仅获取对应键的值「Stag」。

解决方案

只需在生成器表达式中直接指定要提取的键,而不是返回整个字典:

# 直接提取匹配项的patronus值
next(item["patronus"] for item in students if item["patronus"] == "Stag")

执行后会直接返回结果:Stag

额外提示

如果不确定是否存在匹配项,建议给next()添加默认值,避免触发StopIteration异常:

# 无匹配时返回None
next((item["patronus"] for item in students if item["patronus"] == "Stag"), None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:30:23