Python3:统计列表中重复字典的出现次数
问题
我有一个由字典组成的列表,需要统计其中各唯一字典的出现次数。
示例输入:
[{'Basic': 100}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 200}]
期望输出格式:
{'Basic': 100} -> 3 {'Basic': 100, 'Food Allowance': 1000} -> 3 {'Basic': 200} -> 1 OR [index_no] -> count
解决方案
字典属于不可哈希类型,无法直接作为统计工具的键,因此需要先将每个字典转换为可哈希的结构,再进行次数统计。
方法1:转为排序后的键值对元组(推荐)
将字典的键值对排序后转成元组,保证不同顺序的同内容字典会被判定为同一类,再用collections.Counter统计:
from collections import Counter dict_list = [{'Basic': 100}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 200}] # 转换为可哈希的排序元组 hashable_items = [tuple(sorted(d.items())) for d in dict_list] count_result = Counter(hashable_items) # 转换回字典格式输出 for key, count in count_result.items(): print(f"{dict(key)} -> {count}")
运行输出:
{'Basic': 100} -> 3 {'Basic': 100, 'Food Allowance': 1000} -> 3 {'Basic': 200} -> 1
方法2:使用frozenset(不关心键顺序时可用)
如果不介意字典键的顺序,也可以把键值对转成frozenset实现哈希:
from collections import Counter dict_list = [{'Basic': 100}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 200}] hashable_items = [frozenset(d.items()) for d in dict_list] count_result = Counter(hashable_items) for key, count in count_result.items(): print(f"{dict(key)} -> {count}")
输出结果与方法1一致。
方法3:手动遍历统计(无依赖)
不想用collections模块的话,可手动遍历实现统计:
dict_list = [{'Basic': 100}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 200}] count_dict = {} for d in dict_list: key = tuple(sorted(d.items())) count_dict[key] = count_dict.get(key, 0) + 1 for key, count in count_dict.items(): print(f"{dict(key)} -> {count}")
输出[index_no] -> count格式
若需要按唯一字典的首次出现索引输出,可先收集唯一字典列表再统计:
dict_list = [{'Basic': 100}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 100}, {'Basic': 100, 'Food Allowance': 1000}, {'Basic': 200}] unique_dicts = [] seen_keys = set() for d in dict_list: key = tuple(sorted(d.items())) if key not in seen_keys: seen_keys.add(key) unique_dicts.append(d) for idx, item in enumerate(unique_dicts): print(f"[{idx}] -> {dict_list.count(item)}")
运行输出:
[0] -> 3 [1] -> 3 [2] -> 1
内容的提问来源于stack exchange,提问作者Shahzad Nasir
相关产品推荐
相关产品推荐

