[Python-Help] How to get a key from dictionary?
aleaxit at yahoo.com
Tue Mar 26 09:50:46 CET 2002
--- A <printers at sendme.cz> wrote:
> 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
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.
Do You Yahoo!?
Yahoo! Movies - coverage of the 74th Academy Awards®
More information about the Python-list