How to get a key from dictionary? 
Author Message
 How to get a key from dictionary?


Quote:
> 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://www.*-*-*.com/



Sun, 12 Sep 2004 04:41:00 GMT  
 How to get a key from dictionary?
Yes. Good response. Your code is best :)

GBU
Matthew Sherborne



Mon, 13 Sep 2004 05:40:55 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Extracting list of keys from 2-key dictionary

2. Dictionaries and Collections of keys

3. Importing multiople keys into dictionary

4. All components of the primary key must be linked - Dictionary Relationship

5. Integer and String Dictionary Keys for Fast Access

6. Cookbook: Associating multiple values with each key in a dictionary

7. Regular expression as dictionary key?

8. looping through the keys of a dictionary

9. Confusion about dictionaries - keys use value or identity?

10. Walk through dictionary keys?

11. Bug: dictionary with >= 8192 keys not initialized correctly

12. dictionary with complex keys

 

 
Powered by phpBB® Forum Software