Reputation: 4923
I've dictionary which contains values like this {a:3,b:9,c:88,d:3} I want to calculate how many times particular number appears in above dictionary. For example in above dictionary 3 appears twice in dictionary Please help to write python script
Upvotes: 4
Views: 5704
Reputation: 12901
I'd use a defaultdict to do this (basically the more general version of the Counter). This has been in since 2.4.
from collections import defaultdict
counter = defaultdict( int )
b = {'a':3,'b':9,'c':88,'d':3}
for k,v in b.iteritems():
counter[v]+=1
print counter[3]
print counter[88]
#will print
>> 2
>> 3
Upvotes: 1
Reputation: 288298
You should use collections.Counter
:
>>> from collections import Counter
>>> d = {'a':3, 'b':9, 'c':88, 'd': 3}
>>> Counter(d.values()).most_common()
[(3, 2), (88, 1), (9, 1)]
Upvotes: 12