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

如何在JSON格式字典列表中检查值含指定词并提取对应pg_no字段

Python实现方案

1. 通用校验能力实现

该通用方法支持传入任意字典列表、目标校验字段、待匹配关键词,返回所有符合匹配条件的字典,也可根据业务需求调整返回值格式(如仅返回是否存在匹配项)。

def filter_dict_by_keyword(dict_list: list, check_field: str, keyword: str) -> list:
    """
    筛选字典列表中指定字段值包含目标关键词的所有字典
    :param dict_list: 待校验的字典列表
    :param check_field: 要校验的字典字段名
    :param keyword: 待匹配的关键词
    :return: 符合条件的字典组成的列表
    """
    # 如需不区分大小写匹配,可将判断条件改为 keyword.lower() in str(item[check_field]).lower()
    return [item for item in dict_list if check_field in item and keyword in str(item[check_field])]

2. 特定场景筛选:提取text字段含valid的pg_no值

示例数据

test_response = [
    {
        'title': 'some value',
        'pg_no': 1,
        'text': 'Data is not valid'
    },
    {
        'title': 'another title',
        'pg_no': 2,
        'text': 'some random text'
    },
    {
        'title': 'last title',
        'pg_no': 3,
        'text': 'valid data'
    }
]

实现代码

# 调用通用方法筛选text字段包含valid的字典
matched_items = filter_dict_by_keyword(test_response, 'text', 'valid')
# 提取所有符合条件的pg_no值
pg_no_result = [item['pg_no'] for item in matched_items]
print(pg_no_result)

运行结果

输出为:[1, 3]


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:57:02