如何在Python中识别字典列表里name与type均重复的项并输出
问题描述
给定如下Python字典列表:
list1 = [ {'id': 1, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 2, 'name': 'B', 'blob': 'blob', 'type': 'B'}, {'id': 3, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 4, 'name': 'C', 'blob': 'blob', 'type': 'A'}, {'id': 5, 'name': 'E', 'blob': 'blob', 'type': 'A'}, {'id': 6, 'name': 'B', 'blob': 'blob', 'type': 'B'} ]
需求是找出其中name和type值均相同的重复项,并输出如下格式内容:
name A has duplicate type A name B has duplicate type B
此前搜索到的方案大多仅能检测单个字段的重复,如何实现上述需求?
解决方案
核心思路是将name和type组合成一个可哈希的键(比如元组),通过统计该组合键的出现次数来判断是否重复。
方法一:基础字典统计
list1 = [ {'id': 1, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 2, 'name': 'B', 'blob': 'blob', 'type': 'B'}, {'id': 3, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 4, 'name': 'C', 'blob': 'blob', 'type': 'A'}, {'id': 5, 'name': 'E', 'blob': 'blob', 'type': 'A'}, {'id': 6, 'name': 'B', 'blob': 'blob', 'type': 'B'} ] # 初始化统计字典 counts = {} for item in list1: # 用(name, type)作为唯一键 key = (item['name'], item['type']) # 累加计数,不存在则默认0 counts[key] = counts.get(key, 0) + 1 # 筛选并输出重复项 for (name, type_val), count in counts.items(): if count > 1: print(f'name {name} has duplicate type {type_val}')
方法二:使用collections.defaultdict简化统计
如果不想处理键不存在的情况,可以用defaultdict来简化计数逻辑:
from collections import defaultdict list1 = [ {'id': 1, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 2, 'name': 'B', 'blob': 'blob', 'type': 'B'}, {'id': 3, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 4, 'name': 'C', 'blob': 'blob', 'type': 'A'}, {'id': 5, 'name': 'E', 'blob': 'blob', 'type': 'A'}, {'id': 6, 'name': 'B', 'blob': 'blob', 'type': 'B'} ] counts = defaultdict(int) for item in list1: key = (item['name'], item['type']) counts[key] += 1 # 输出重复项 for (name, type_val), count in counts.items(): if count > 1: print(f'name {name} has duplicate type {type_val}')
两种方法运行后都会输出符合要求的结果,核心是通过组合字段作为键来实现多字段的重复检测。
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

