get keys with the same values

Duncan Booth duncan.booth at invalid.invalid
Thu Jun 12 14:23:03 CEST 2008


Nader <n.emami at gmail.com> wrote:

> I have a dictionary and will get all keys which have the same values.
> 
> d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> 
> I will something as :
> 
> d.keys(where their values are the same)
> 
> With this statement I can get two lists for this example:
> l1= ['a','e']
> l2=['b','d']
> 
> Would somebody tell me how I can do it?

Here's one way:

>>> import itertools, functools, operator
>>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>>> get = functools.partial(operator.getitem, d)
>>> for (k,v) in itertools.groupby(sorted(d, key=get), key=get):
	print k, list(v)

	
1 ['a', 'e']
2 ['c']
3 ['b', 'd']
4 ['f']

or if you want a dictionary:

>>> dict((k,list(v)) for (k,v) in
    itertools.groupby(sorted(d, key=get), key=get))
{1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']}

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list