如何在字典列表中筛选仅含custom值为two的id
解决方法
原代码问题分析
你的代码仅筛选出了所有custom值为two的单个条目,但未排除那些同时存在custom值为one的id,因此会把id=1、3这类不符合要求的条目也输出。
正确实现步骤
要满足需求,需先按id分组收集所有对应的custom值,再筛选出仅包含two的id:
list1 = [ {'id': 1, 'custom': 'one'}, {'id': 2, 'custom': 'two'}, {'id': 3, 'custom': 'one'}, {'id': 1, 'custom': 'two'}, {'id': 3, 'custom': 'two'}, {'id': 4, 'custom': 'one'}, {'id': 5, 'custom': 'two'}, ] # 1. 按id分组,用集合存储每个id的所有custom值(自动去重) id_custom_map = {} for entry in list1: uid = entry['id'] if uid not in id_custom_map: id_custom_map[uid] = set() id_custom_map[uid].add(entry['custom']) # 2. 筛选出仅包含'two'的id valid_ids = [uid for uid, customs in id_custom_map.items() if customs == {'two'}] # 3. 输出结果(可选择输出id或对应条目) print("符合要求的id:", valid_ids) # 输出对应条目: for entry in list1: if entry['id'] in valid_ids: print(entry)
输出结果
符合要求的id: [2, 5] {'id': 2, 'custom': 'two'} {'id': 5, 'custom': 'two'}
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

