get keys with the same values

Nader n.emami at gmail.com
Thu Jun 12 14:00:24 CEST 2008


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. And not
the keys that have value more than 1!

Nader



More information about the Python-list mailing list