Clustering the keys of a dict according to its values

Gerard flanagan grflanagan at gmail.com
Sun Nov 16 13:20:54 CET 2008


Florian Brucker wrote:

> Florian Brucker wrote:
>> Hi everybody!
>>
>> Given a dictionary, I want to create a clustered version of it, 
>> collecting keys that have the same value:
>>
>>  >>> d = {'a':1, 'b':2, 'c':1, 'd':1, 'e':2, 'f':3}
>>  >>> cluster(d)
>> {1:['a', 'c', 'd'], 2:['b', 'e'], 3:['f']}
>>
>> That is, generate a new dict which holds for each value of the old 
>> dict a list of the keys of the old dict that have that very value.
>>
>> Another requirement is that it should also work on lists, in that case 
>> with indices instead of keys. We may assume that all values in the 
>> original dict/list can be used as dict keys.
>>

[...]

 > Wow, thanks everybody! There's a lot to learn for me from these 
examples...
 >
 >


d = {'a':1, 'b':2, 'c':1, 'd':1, 'e':2, 'f':3}

from itertools import groupby

d2 = dict(
         (key, [G[1] for G in g]) for (key, g) in
             groupby(
                 sorted( (val, key) for (key, val) in d.iteritems() ),
                 lambda X: X[0]
             )
     )

print d2


{1: ['a', 'c', 'd'], 2: ['b', 'e'], 3: ['f']}


;-) *ducks*

G.




More information about the Python-list mailing list