Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...