Rajeev
Rajeev

Reputation: 46979

counting values in python

How to count the number of occurrence of a values in a dictionary in python

a = dict()
a['cat'] =      1
a['fish'] =     1
a['dog'] =      2  
a['bat'] =      3
a['aardvark'] = 3
a['lion'] =    4  
a['wallaby'] =  5
a['badger'] =   5

output Expected:

KEY  Count
 1   2
 2   1
 3   2
 4   1
 5   2 

EDIT

Sorry , i meant to say counting values

Upvotes: 0

Views: 372

Answers (6)

Benedict
Benedict

Reputation: 2821

You can do this very easily without importing anything:

results={}
for v in a.values():
   results[v]=results.get(v, 0) + 1

for k,v in results.items():
    print k,v

Output:

1 2
2 1
3 2
4 1
5 2

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124758

I suspect you want to use collections.Counter; it let's you handle most counting use cases with ease.

from collections import Counter
a = dict()
a['cat'] =      1
a['fish'] =     1
a['dog'] =      2  
a['bat'] =      3
a['aardvark'] = 3
a['lion'] =    4  
a['wallaby'] =  5
a['badger'] =   5

print Counter(a.values())    

Output: Counter({1: 2, 3: 2, 5: 2, 2: 1, 4: 1})

Or, to format it a little for you:

for key, value in Counter(a.values()).most_common():
    print key, value

Output:

1 2
3 2
5 2
2 1
4 1

Or, to match your output exactly:

for key, value in sorted(Counter(a.values()).items()):
    print key, value

Here we sorted on the key (numbers 1 through 5).

Upvotes: 3

Lee Netherton
Lee Netherton

Reputation: 22552

If you want the sum of the values do:

sum(a.values())

If you want the frequency of the number of occurrences do:

from collections import Counter
Counter(a.values()).items()

Upvotes: 0

mgilson
mgilson

Reputation: 310227

a collections.Counter is the best tool for this job (see answer by Martijn Pieters) -- however, it was introduced in python 2.7. If you need a 2.5+ solution:

from collections import defaultdict
d=defaultdict(int)
for v in a.values():
    d[v]+=1

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

>>> from collections import Counter
>>> Counter(a.values())
Counter({1: 2, 3: 2, 5: 2, 2: 1, 4: 1})

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142226

I have a horrible feeling, and while it's unclear, that len(a) might be an answer...

However, it's also possible that:

from collections import Counter
Counter(a.values())

is also likely.

Upvotes: 0

Related Questions