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

Alex Martelli aleaxit at yahoo.com
Tue Mar 26 15:41:00 EST 2002


--- Matthew Sherborne <miracle at paradise.net.nz> wrote:
> 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

Apart from the crucial defects of [a] returning a
"random" key if more than one has the sought-for
value and [b] not knowing when None is returned
if no key was found OR None was the "random" key,
this is NOT faster than looping on dict, or even, if
you are stuck with old (<2.2) Python, at least on
dict.keys().  dict.items() must prepare a list of N
tuples, and that's typically slower than it
takes to do N key-to-value lookups.  And let's not
even get into using the name of a built-in type
(dict) as a GLOBAL variable, as this code seems to
be doing.  dict is only a built-in in 2.2 and later,
but there's no reason to use it even for
earlier releases, and it does risk messing some
things up.  If you must have a global (and you
shouldn't), call it adict, thedict, somedict, ...

I keep suggesting:

def findKeys(adict, aval):
    return [k for k in adict if adict[k]==aval]

or the obvious equivalent with adict.keys() if
you're stuck with some old Python such as 2.1.

Returning a list is obviously the right approach
since you're returning something of which there
could be 0, 1, 2, ..., N occurrences.  And a
list is built easily and fast with a list
comprehension.  So, why not?


Alex


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




More information about the Python-list mailing list