In article <[EMAIL PROTECTED]>, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Jun 12, 6:41 am, David C. Ullrich <[EMAIL PROTECTED]> wrote: > > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]> > > 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
-- http://mail.python.org/mailman/listinfo/python-list