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

如何在Python中从字典列表查询指定字段值?

实现Python字典列表的多条件灵活查询

刚好我之前处理过类似的需求,这种场景写一个通用查询函数是最方便的——既能适配不同的查询条件,还能自动处理重复条目,返回所有符合要求的结果。

先看咱们的原始数据:

heroes = [
    {'id':'001', 'actor_name':'Chris Evans', 'hero_name':'Captain America'},
    {'id':'002', 'actor_name':'Chris Hemsworth', 'hero_name':'Thor'},
    {'id':'003', 'actor_name':'Robert Downey', 'hero_name':'Iron Man'},
    {'id':'004', 'actor_name':'Don Cheadle', 'hero_name':'War Machine'},
    {'id':'005', 'actor_name':'Jeremy Renner', 'hero_name':'Hawkeye'},
    # 加个重复id的测试条目,模拟重复场景
    {'id':'001', 'actor_name':'Chris Evans', 'hero_name':'Captain America (Alternate)'}
]

通用查询函数实现

这个函数的核心思路是:接收英雄列表、要返回的字段名,以及任意数量的查询条件,遍历每个英雄条目逐一校验,把符合所有条件的目标字段值收集起来返回。

def query_heroes(heroes_list, return_field, **query_conditions):
    results = []
    for hero in heroes_list:
        # 检查当前英雄是否满足所有传入的查询条件
        is_match = True
        for condition_key, condition_value in query_conditions.items():
            if hero.get(condition_key) != condition_value:
                is_match = False
                break
        if is_match:
            results.append(hero.get(return_field))
    return results

实际使用示例

  1. 查询演员名为'Don Cheadle'且英雄名为'War Machine'的英雄id
result = query_heroes(heroes, 'id', actor_name='Don Cheadle', hero_name='War Machine')
print(result)  # 输出: ['004']
  1. 查询id为'001'的英雄名
    因为我们加了重复id的测试条目,函数会自动返回所有符合条件的结果:
result = query_heroes(heroes, 'hero_name', id='001')
print(result)  # 输出: ['Captain America', 'Captain America (Alternate)']

额外说明

  • 这个函数灵活性很高,你可以任意组合查询条件——比如只按actor_name查询,或者同时按id+hero_name过滤都没问题
  • 如果没有符合条件的条目,函数会返回空列表[],避免报错,后续处理更安全

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:58