Python 2.7 Counting number of dictionary items with given value
Python 2.7 Counting number of dictionary items with given value
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Question
01:15 Accepted answer (Score 36)
02:32 Answer 2 (Score 11)
03:03 Thank you
--
Full question
https://stackoverflow.com/questions/1346...
Question links:
[How many items in a dictionary share the same value in Python]: https://stackoverflow.com/questions/2393...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
ACCEPTED ANSWER
Score 36
This first part is mostly for fun -- I probably wouldn't use it in my code.
sum(d.values())
will get the number of True values. (Of course, you can get the number of False values by len(d) - sum(d.values())).
Slightly more generally, you can do something like:
sum(1 for x in d.values() if some_condition(x))
In this case, if x works just fine in place of if some_condition(x) and is what most people would use in real-world code)
OF THE THREE SOLUTIONS I HAVE POSTED HERE, THE ABOVE IS THE MOST IDIOMATIC AND IS THE ONE I WOULD RECOMMEND
Finally, I suppose this could be written a little more cleverly:
sum( x == chosen_value for x in d.values() )
This is in the same vein as my first (fun) solution as it relies on the fact that True + True == 2. Clever isn't always better. I think most people would consider this version to be a little more obscure than the one above (and therefore worse).
ANSWER 2
Score 11
If you want a data structure that you can quickly access to check the counts, you could try using a Counter (as @mgilson points out, this relies on the values themselves being hashable):
>>> from collections import Counter
>>> d = {(1, 2): 2, (3, 1): 2, (4, 4): 1, (5, 6): 4}
>>> Counter(d.values())
Counter({2: 2, 1: 1, 4: 1})
You could then plug in a value and get the number of times it appeared:
>>> c = Counter(d.values())
>>> c[2]
2
>>> c[4]
1