Python: counting duplicate dictionary values

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 ​​for each test, regardless of units?

i.e.

in 'test1' there is 2x 'alpha', 1x 'delta'

in 'test2' there is 1x 'beta', 2x 'gamma'

Any inputs?

Thank you very much.

+4
source share
1 answer

In Python 2.7 or 3.1 or higher, 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}) 
+9
source

Source: https://habr.com/ru/post/1345921/


All Articles