
Try/Except vs. If in Dictionary Key Access Python Performance - ilhicas
https://ilhicas.com/2018/04/25/Python-try-vs-if-in-dict-access.html
======
dozzie
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)?

~~~
ilhicas
Hello, I've had Data Structures, while on BSc and implemented by hand
hashmaps.. If you read the post you would understand the doubt.

Try the following:

a = [i for in range(10000)] if 9999 in a: print('yay I just looped over an
entire array')

however:

a = {i:i for in range(10000)} if 9999 in a: print('yay I found a key in linear
time')

Now, You might be an expert in Data Structures, but what makes you implicitly
know how the 'IN' behaves in python, and that it won't convert to the keys()
method of the dict to get a list with the same behaviour as in a list?

~~~
dozzie
> [...] what makes you implicitly know how the 'IN' behaves in python, and
> that it won't convert to the keys() method of the dict to get a list with
> the same behaviour as in a list?

Because it would be the dumb way to do it. You have a lookup procedure to
extract a value from a hash. A procedure to check if the key is present in the
hash will look exactly the same, barring the value being returned.

Libraries usually work the same way as you would write yourself if you were
trained in the task, so it's easy to guess.

~~~
ilhicas
Have you ever read PEP-20 aka The Zen of Python?

I'll quote part of it, regarding your "so it's easy to guess"

"In the face of ambiguity, refuse the temptation to guess."

Source:
[https://www.python.org/dev/peps/pep-0020/](https://www.python.org/dev/peps/pep-0020/)

------
carapace
Use try..except.. when you expect it to mostly succeed.

    
    
        $ 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
    
    

"try" is _fast_ , "except" is slow

~~~
ilhicas
Thanks for the input, yes I've since read that the problem lies on the
exception catch, and definitely the time toll is in it.

