Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 'gamma'

Any inputs?

Many Thanks.

like image 982
siva Avatar asked Jan 21 '23 03:01

siva


1 Answers

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})
like image 109
Sven Marnach Avatar answered Jan 28 '23 21:01

Sven Marnach