Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many items in a dictionary share the same value in Python

Is there a way to see how many items in a dictionary share the same value in Python?

Let's say that I have a dictionary like:

{"a": 600, "b": 75, "c": 75, "d": 90}

I'd like to get a resulting dictionary like:

{600: 1, 75: 2, 90: 1}

My first naive attempt would be to just use a nested-for loop and for each value then I would iterate over the dictionary again. Is there a better way to do this?

like image 697
Jared Avatar asked Mar 06 '10 19:03

Jared


3 Answers

You could use itertools.groupby for this.

import itertools
x = {"a": 600, "b": 75, "c": 75, "d": 90}
[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]
like image 194
Wolph Avatar answered Oct 31 '22 22:10

Wolph


When Python 2.7 comes out you can use its collections.Counter class

otherwise see counter receipe

Under Python 2.7a3

from collections import Counter
items = {"a": 600, "b": 75, "c": 75, "d": 90}    
c = Counter( items )

print(  dict( c.items() ) )

output is

{600: 1, 90: 1, 75: 2}

like image 31
mmmmmm Avatar answered Oct 31 '22 20:10

mmmmmm


>>> a = {"a": 600, "b": 75, "c": 75, "d": 90}
>>> b = {}
>>> for k,v in a.iteritems():
...     b[v] = b.get(v,0) + 1
...
>>> b
{600: 1, 90: 1, 75: 2}
>>>
like image 25
MattH Avatar answered Oct 31 '22 20:10

MattH