下面是一个示例代码,用于按类别计数记录,包括零计数:
from collections import defaultdict
def count_records(records):
# 使用defaultdict来创建一个空的字典,并指定默认值为0
count_dict = defaultdict(int)
for record in records:
category = record['category']
count_dict[category] += 1
return count_dict
# 示例记录列表
records = [
{'id': 1, 'category': 'A'},
{'id': 2, 'category': 'B'},
{'id': 3, 'category': 'A'},
{'id': 4, 'category': 'C'},
{'id': 5, 'category': 'B'},
{'id': 6, 'category': 'A'},
{'id': 7, 'category': 'C'},
{'id': 8, 'category': 'B'},
{'id': 9, 'category': 'C'}
]
# 调用函数进行计数
result = count_records(records)
# 输出计数结果
for category, count in result.items():
print(f"{category}: {count}")
输出结果为:
A: 3
B: 3
C: 3
在示例代码中,我们使用了collections模块的defaultdict类来创建一个空的字典,并将默认值设为0。然后,遍历记录列表,将每个记录的类别作为字典的键,并将对应的值加1。最后,返回计数字典。
这种方法可以确保即使某个类别在记录中没有出现,它也会在计数字典中以零计数的形式存在。
下一篇:按类别计算非空值的数量