[Tutor] How to get a key from dictionary?

dman dman@dman.ddts.net
Mon, 25 Mar 2002 16:59:01 -0600


On Mon, Mar 25, 2002 at 11:16:28PM +0100, 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')

That is not how dictionaries are intended to be used.  It is possible,
with a little work and a few CPU cycles, to work backwards like that.
If you give more details regarding why you want to do this then
perhaps we can suggest a more efficient solution.  In the meantime,

a_dict = { 'aa' : 1 , 'bb' : 2 }
items = a_dict.items()
VALUE = 1 # the value you want to find
t = filter( lambda x : x[1] == VALUE , items )[0]
key = t[0]
print key


What this does it get the list of (key,value) tuples from the
dictionary, then iterate over it finding all the pairs that have the
value you want to find.  It then takes the first of those (bear in mind
dicts can have duplicate values but not duplicate keys) and prints the
key for that pair.  This algorithm requires linear time.  As the
dictionary grows larger the time for this code to execute grows at the
same rate.

Also note that using 'dict' as a variable name is not recommended
since it is a built-in name in python >= 2.2.

HTH,
-D

-- 

Micros~1 :  
 For when quality, reliability 
  and security just aren't
   that important!