Python: Counting repeating values of a dictionary

空扰寡人 提交于 2019-12-23 12:44:30

问题


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.


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


来源:https://stackoverflow.com/questions/5490078/python-counting-repeating-values-of-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!