get keys with the same values

David C. Ullrich dullrich at sprynet.com
Thu Jun 12 19:56:25 CEST 2008


In article 
<d4bcc08a-3810-474c-9978-e60e3ef6ee82 at p25g2000hsf.googlegroups.com>,
 Nader <n.emami at gmail.com> wrote:

> On Jun 12, 1:41 pm, 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.
> >
> > >d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> >
> > That's not a dictionary, it's a syntax error. If you actually
> > have a dictionary you could say
> >
> > 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]
> >
> > Possibly dd is now what you really want; if you really
> > want what you said you want you could use
> >
> > [l for l in dd.values() if len(l) > 1]
> >
> > >I will something as :
> >
> > >d.keys(where their values are the same)
> >
> > >With this statement I can get two lists for this example:
> > >l1= ['a','e']
> > >l2=['b','d']
> >
> > >Would somebody tell me how I can do it?
> >
> > >Regards,
> > >Nader
> >
> > David C. Ullrich
> 
> Thank for your type about the syntax error. This an example example,
> the keys of my dictionary are tuples:
> d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08,
> 30.99) : 1}
> 
> But what I will is to get all keys which has the same valus.

That's exactly what the code I posted does.

> And not
> the keys that have value more than 1!

It doesn't do that. Or if you prefer, it doesn't do that!

Instead of looking at it and trying to figure out what it does,
which of course can be tricky, try _running_ the code.
Then print dd. Then print [l for l in dd.values() if len(l) > 1] .

> 
> Nader

-- 
David C. Ullrich



More information about the Python-list mailing list