Python: Counting repeating values of a dictionary
I have a dictionary as follows:
dictA = { ('unit1','test1') : 'alpha' , ('unit1','test2') : 'beta', ('unit2','test1') : 'alpha', ('unit2','test2') : 'gamma' , ('unit3','test1') : 'delta' , ('unit3','test2') : 'gamma' }
How can I count the number of repeating values per each test independent of units?
i.e.
in 'test1' there is 2x 'alpha', 1x 'delta'
in 'test2' there is 1x 'beta', 2x '开发者_StackOverflow社区gamma'
Any inputs?
Many Thanks.
In Python 2.7 or 3.1 or above, you can use collections.Counter
:
from collections import Counter
counts = Counter((k[1], v) for k, v in dictA.iteritems())
print(counts)
prints
Counter({('test1', 'alpha'): 2, ('test2', 'gamma'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1})
精彩评论