Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating frequency of values in dictionary

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

like image 440
username_4567 Avatar asked Dec 12 '22 05:12

username_4567


2 Answers

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)]
like image 200
phihag Avatar answered Dec 28 '22 17:12

phihag


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
like image 37
Matt Alcock Avatar answered Dec 28 '22 15:12

Matt Alcock