[Tutor] Re: [Python-Help] How to get a key from dictionary?

Alex Martelli aleaxit@yahoo.com
Tue, 26 Mar 2002 00:50:46 -0800 (PST)


--- A <printers@sendme.cz> wrote:
> Hi,
> Is there a possibility to get, from a dictionary, a
> key according to a value ?

In general, zero or more keys will correspond to
a given value, and it's easy to get the list of those
(but of course it takes time proportional to the
TOTAL number of items in the dictionary):

[ key for key in thedict if thedict[key] == avalue ]

This is Python 2.2, but it's not hard to do it in
Python 2.1 (or even 2.0) just as well, e.g.:

[ key for key, v in thedict.items() if v == avalue ]

just a bit slower for huge dictionaries given the
need to call .items().


> For example
> I have a dictionary
> 
> dict={'aa':1,'bb':2}

I STRONGLY suggest you don't use the name of built-in
types as the name of your variables.  Don't call your
variables: list, dict, tuple, int, long, float, str...
Python lets you do that, but sooner or later you'll
come a doozy.  Use alist, adict, ... or else
thelist, thedict, ....  dict is a built-in name
only since Python 2.2, by the way.


Alex


__________________________________________________
Do You Yahoo!?
Yahoo! Movies - coverage of the 74th Academy Awards®
http://movies.yahoo.com/