Skip to content
Advertisement

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

If I have got something like this:

JavaScript

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?

Advertisement

Answer

As mentioned in THIS ANSWER using operator.countOf() is the way to go but you can also use a generator within sum() function as following:

JavaScript

Or as a slightly more optimized and functional approach you can use map function by passing the __eq__ method of the integer as the constructor function.

JavaScript

Benchmark:

JavaScript

Note that although using map function in this case may be more optimized, but in order to have a more comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then, you can use the most proper approach based on the structure and amount of data you have.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement