Python:计算字典中重复值的数量
我有一个字典,内容如下:
dictA = { ('unit1','test1') : 'alpha' , ('unit1','test2') : 'beta', ('unit2','test1') : 'alpha', ('unit2','test2') : 'gamma' , ('unit3','test1') : 'delta' , ('unit3','test2') : 'gamma' }
我该如何计算每个测试中重复值的数量,而不考虑单位呢?
也就是说:
在'test1'中,有2个'alpha',1个'delta'
在'test2'中,有1个'beta',2个'gamma'
有没有什么建议?
非常感谢。
1 个回答
9
在Python 2.7或者3.1及以上版本中,你可以使用 collections.Counter
这个工具:
from collections import Counter
counts = Counter((k[1], v) for k, v in dictA.iteritems())
print(counts)
输出结果是
Counter({('test1', 'alpha'): 2, ('test2', 'gamma'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1})