Python 2.7 dictionary presence

I want to check the presence of a key in the dictionary as "if the key is not in the dictionary: do something", I have already done this several times, but this time it behaves strangely.

in particular:

termCircuit = termCircuitMap[term] 

returns KeyError

when I debugged this code in Eclipse PyDev, I got the following (using expressions):

 term in termCircutiMap # prints False term in termCircuitMap.keys() # prints True 

Does anyone understand how this is possible? I thought that if something is "in" the key set, then it is "in" the dictionary.

I am enclosing a rating screenshot.

http://img836.imageshack.us/img836/1274/screenshotpython.png

Thanks so much for the explanation :)

+8
python
source share
1 answer

You can see this behavior if your key __hash__ function __hash__ not defined properly. For example, the following gives roughly the same behavior as you describe:

 import random class Evil(int): def __hash__(self): return random.randint(0, 10000) evil_vals = [Evil(n) for n in range(10)] dict_with_evil_keys = dict((evil_val, None) for evil_val in evil_vals) print evil_vals[0] in dict_with_evil_keys # prints False print evil_vals[0] in dict_with_evil_keys.keys() # prints True 

In this case, I generate random hash values, which is obviously a bad idea. A less obvious problem that would have the same effect could be if your key values ​​are mutable. (In general, mutable values ​​should never define __hash__ and should not be used as keys in dictionaries.)

+11
source share

All Articles