How to get a key from dictionary?

Matthew Sherborne miracle at paradise.net.nz
Tue Mar 26 15:28:38 EST 2002


Sorry to be a show off, but I reckon that this way may be faster. Sorry again. The other replies are very helpful.  :)

def findKey(val):
  for key, value in dict.items():
    if value == val: return key
  return None
  
GBU
Matthew Sherborne

----- Original Message ----- 
From: "Don Arnold" <darnold02 at sprynet.com>
To: <printers at sendme.cz>; <python-list at python.org>; <tutor at python.org>; <activepython at listserv.activestate.com>; <python-help at python.org>
Sent: Tuesday, March 26, 2002 11:51 AM
Subject: Re: How to get a key from dictionary?


> >>> targetval = 2
> >>> dict = {'aa':1, 'bb':2, 'cc': 3, 'dd': 1}
> >>> targetval = 2
> >>> for key in dict.keys():
>           if dict[key] == targetval:
>             print "found", targetval, "at key", key
> 
> found 2 at key bb
> >>> targetval = 1
> >>> for key in dict.keys():
>           if dict[key] == targetval:
>             print "found", targetval, "at key", key
> 
> found 1 at key aa
> found 1 at key dd
> 
> ----- Original Message -----
> From: "A" <printers at sendme.cz>
> To: <python-list at python.org>; <tutor at python.org>;
> <activepython at listserv.activestate.com>; <python-help at python.org>
> Sent: Monday, March 25, 2002 4:16 PM
> Subject: How to get a key from dictionary?
> 
> 
> > 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')
> >
> > Thank you for help
> > Ladislav
> >
> >
> > _______________________________________________
> > ActivePython mailing list
> > ActivePython at listserv.ActiveState.com
> > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
> 
> _______________________________________________
> ActivePython mailing list
> ActivePython at listserv.ActiveState.com
> To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20020327/a67fedc2/attachment.html>


More information about the Python-list mailing list