如何在Python字典列表中查找含指定type值的字典并返回其app值
解决方案
我们可以通过遍历列表匹配type字段取值实现需求,以下是两种常用的实现方式:
1. 通用遍历写法(可读性高,适合复杂逻辑扩展)
该写法会优先返回第一个匹配到type值的字典的app字段,未匹配到则返回None,同时做了异常兼容,避免字典缺少对应键时报错:
def get_app_by_type(group_list, target_type): for item in group_list: if item.get('type') == target_type: return item.get('app') return None
调用示例
# 查询type为app_group2对应的app字段 print(get_app_by_type(group_list, 'app_group2')) # 输出:['slack', 'Discord', 'zoom', 'vs code']
2. 简化生成器写法(适合单行查询场景)
target_type = 'app_group3' # 未匹配到时默认返回None,可自行修改第二个参数调整默认返回值 result = next((item['app'] for item in group_list if item.get('type') == target_type), None) print(result) # 输出:['calculater', 'google']
特殊场景兼容
如果你的业务场景允许列表中存在多个相同type取值的字典,可以用列表推导式收集所有匹配结果:
def get_all_app_by_type(group_list, target_type): return [item.get('app') for item in group_list if item.get('type') == target_type]
内容的提问来源于stack exchange,提问作者mona alobisat
相关产品推荐
相关产品推荐

