Skip to content Skip to sidebar Skip to footer

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') : '

Solution 1:

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})

Post a Comment for "Python: Counting Repeating Values Of A Dictionary"