get keys with the same values

Nader n.emami at gmail.com
Thu Jun 12 14:15:28 CEST 2008


On Jun 12, 2:05 pm, Chris <cwi... at gmail.com> wrote:
> On Jun 12, 1:48 pm, Nader <n.em... at gmail.com> wrote:
>
>
>
> > On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote:
>
> > > Nader:
>
> > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> > > > I will something as :
> > > > d.keys(where their values are the same)
>
> > > That's magic.
>
> > > > 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?
>
> > > You can create a new dict where the keys are the values of the input
> > > dict and the values are a list of the keys of the original dict. So
> > > scanning the keys, values of the input dict, you can fill the second
> > > dict. Then you can scan the second dict, and create a list that
> > > contains only value lists longer than one.
>
> > > Bye,
> > > bearophile
>
> > Is it niet possible with one or two statement, maybe with list
> > comprehension. For exmple:
>
> > l = [(k,v) for k in d.keys() for v in d.values() | en here we need
> > some extra logic (v = 1)]
>
> > I don;t konw how we can define a logic statement in a list
> > comprehension.
> > It will be very compact, if it would possible.
>
> > Nader
>
> If you are going to use this reverse look-up alot you'd be better off
> building another dictionary with the original values being keys and
> the original keys being values, if it is used infrequently enough you
> can search for it with result_list = [k for k,v in dictionary.items()
> if v == search_value]

Thank you! It is the anwser which I was looking for. [(k,v) for k,v
in  d.items() if v is pattern].
But I don't understand what tou mean of "reverse look-up a lot"! I
have to read some informations inclusive (latitudes and longitudes)
form a file and after some processing to save part of this information
to other file.
Why do I make a new dictionary?

Nader



More information about the Python-list mailing list