This is exactly why you need to take some algorithms and data structures
lecture. Who in their right mind would think that checking if a key is present
in a hash map takes O(n) time by generating a list of all keys and linear
search when extracting the value from under that key takes O(1)?
Use try..except.. when you expect it to mostly succeed.<p><pre><code> $ python -m timeit -s "a={k:k for k in range(10000)}" 'try:
b=a[10001]
except:
pass'
1000000 loops, best of 3: 0.276 usec per loop
$ python -m timeit -s "a={k:k for k in range(10000)}" 'try:
b=a[1]
except:
pass'
10000000 loops, best of 3: 0.0255 usec per loop
</code></pre>
"try" is <i>fast</i>, "except" is slow