count the number of occurrences of a certain value in a dictionary in python?

我只是一个虾纸丫 提交于 2019-11-30 23:41:16

问题


If I have got something like this:

D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

If I want for example to count the number of occurrences for the "0" as a value without having to iterate the whole list, is that even possible and how?


回答1:


As I mentioned in comments you can use a generator within sum() function like following:

sum(value == 0 for value in D.values())

Or as a slightly more optimized and functional approach you can use map function as following:

sum(map((0).__eq__, D.values()))

Benchmark:

In [56]: %timeit sum(map((0).__eq__, D.values()))
1000000 loops, best of 3: 756 ns per loop

In [57]: %timeit sum(value == 0 for value in D.values())
1000000 loops, best of 3: 977 ns per loop

Note that although using map function in this case may be more optimized but in order to achieve a comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then you can decide when to use which in order to gain the more performance.




回答2:


Alternatively, using collections.Counter:

from collections import Counter
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

Counter(D.values())[0]
# 3



回答3:


You can count it converting it to a list as follows:

D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
print(list(D.values()).count(0))
>>3

Or iterating over the values:

print(sum([1 for i in D.values() if i == 0]))
>>3


来源:https://stackoverflow.com/questions/48371856/count-the-number-of-occurrences-of-a-certain-value-in-a-dictionary-in-python

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