简体   繁体   English

Python:计算字典的重复值

[英]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? 如何计算每个测试的重复值的数量,与单位无关?

ie

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

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

Any inputs? 有什么投入?

Many Thanks. 非常感谢。

In Python 2.7 or 3.1 or above, you can use collections.Counter : 在Python 2.7或3.1或更高版本中,您可以使用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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM