get keys with the same values

Paul McGuire ptmcg at austin.rr.com
Thu Jun 12 15:45:56 CEST 2008


On Jun 12, 6:41 am, David C. Ullrich <dullr... at sprynet.com> wrote:
> On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.em... at gmail.com>
> wrote:
>
> >Hello,
>
> >I have a dictionary and will get all keys which have the same values.
>
<snip>
>
> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>
> dd = {}
>
> for key, value in d.items():
>   try:
>     dd[value].append(key)
>   except KeyError:
>     dd[value] = [key]
>
<snip>

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']

-- Paul



More information about the Python-list mailing list