get keys with the same values

Nick Craig-Wood nick at craig-wood.com
Thu Jun 12 15:31:05 EDT 2008


Paul McGuire <ptmcg at austin.rr.com> wrote:
>  Instead of all that try/except noise, just use the new defaultdict:
> 
> >>> from collections import defaultdict
> >>>
> >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
> >>>
> >>> dd = defaultdict(list)
> >>> for key, value in d.items():
>  ...     dd[value].append(key)
>  ...
> >>> for k,v in dd.items():
>  ...     print k,':',v
>  ...
>  1 : ['a', 'e']
>  2 : ['c']
>  3 : ['b', 'd']
>  4 : ['f']
> 

Or use the little understood dict.setdefault method which has been
with us from time immemorial...

>>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>>> dd = {}
>>> for k, v in d.items():
...     dd.setdefault(v, []).append(k)
...
>>> dd
{1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']}
>>>

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list