get keys with the same values

David C. Ullrich dullrich at sprynet.com
Thu Jun 12 13:57:52 EDT 2008


In article 
<3fdafa74-2043-4052-bdec-843f69d9e5fa at e39g2000hsf.googlegroups.com>,
 Paul McGuire <ptmcg at austin.rr.com> wrote:

> 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:

That's certainly much better. The machine where I am in
the early morning is still stuck with Python 1.5.3...

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

-- 
David C. Ullrich



More information about the Python-list mailing list