How to get a key from dictionary?

Peter Hansen peter at engcorp.com
Mon Mar 25 19:59:41 EST 2002


A wrote:
> 
> Hi,
> Is there a possibility to get, from a dictionary, a key according to a
> value ?
> For example
> I have a dictionary
> 
> dict={'aa':1,'bb':2}
> 
> and
> dict['aa']
> is 1
> 
> But how can I for value 1 find out  key? (That is here  'aa')

If you've seen the other responses, you've learned about the issues.
One possible solution I haven't seen suggested is that you simply
populate two dictionaries, one for each direction.  This of course
works only if you have unique values as well as unique keys.

If you wrap the two dictonaries inside a class that handles the
hard work for you, you can make it appear that you have a regular
dictionary but which lets you retrieve in both directions.

-Peter



More information about the Python-list mailing list