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

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


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 loopIn [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 more performance.


Alternatively, using collections.Counter:

from collections import CounterD = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}Counter(D.values())[0]# 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