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

如何从包含多个单键值对字典的列表中按指定键提取值

解决方案

方法1:遍历匹配(可读性最高,全版本兼容)

逐个遍历列表内的字典,匹配到目标键就返回对应值,找到后直接终止遍历避免无效计算:

List1 = [{'dept': 'a'}, {'country': 'India'}, {'name':'xyz'}, {'age':32}]
target_key = "name"
result = None

for item in List1:
    if target_key in item:
        result = item[target_key]
        break

print(result) # 输出:xyz

方法2:生成器表达式(最简洁,支持默认值)

用next()配合生成器表达式一行完成,找不到目标键时可自定义默认返回值,不会抛出异常:

List1 = [{'dept': 'a'}, {'country': 'India'}, {'name':'xyz'}, {'age':32}]
target_key = "name"
# 第二个参数为匹配失败时的默认返回值,可按需修改
result = next((item[target_key] for item in List1 if target_key in item), None)

print(result) # 输出:xyz

方法3:列表推导(适配多匹配结果场景)

如果列表中存在多个包含目标键的字典,可用列表推导提取所有匹配的值:

List1 = [{'dept': 'a'}, {'country': 'India'}, {'name':'xyz'}, {'age':32}, {'name':'abc'}]
target_key = "name"
result = [item[target_key] for item in List1 if target_key in item]

print(result) # 输出:['xyz', 'abc']

注意事项

  • 以上所有方法都不需要提前知道目标字典的索引位置,完全通过键名匹配取值
  • 方法1和方法2只会返回第一个匹配到的目标值,适合单匹配场景;方法3会返回所有匹配值,适合多匹配场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:27:01