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

RowanX picture RowanX · Jan 21, 2018 · Viewed 42.8k times · Source

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?

Answer

Kasravnd picture Kasravnd · Jan 21, 2018

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.