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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.