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
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)]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With