Home Try/Except vs If in Dictionary Key access Python Performance
Post
Cancel

Try/Except vs If in Dictionary Key access Python Performance

So, recently while testing some coding I questioned myself, what would be better performance wise, if trying to access a dictionary key directly with a try/except strategy or if I would make use of If key in access.

This question has to do with my lack of knowledge on the ìf behaviour in the below statement:

1
2
if key in dictionary:
    #do Something with dict and key here

My initial thought was, well it should behave similar to a search in an array, as this was what I thought it would translate to:

1
2
if key in dictionary.keys():
    #This would have returned an array, losing the O(1) properties of hashmaps for lookups

So, I thougt, well, then let’s try to access it and just catch an error if the key doesn’t exist, this is meant for a very high request rate and we should keep our lookups low:

1
2
3
4
try:
    dictionary[key]
except KeyError as e:
    pass

Well, and that was it.. I thought.. I was very wrong.

Eventually while iterating on the method, I got the question again. This time I tested it.

So how to test performance of both statements?

Well, let’s open a python shell and find out using the timeit module.

So first lets try the Try/Except block

1
2
3
4
import timeit

timeit.timeit(setup="a={k:k  for k in range(10000)}",stmt="try:\n   b=a[10001]\nexcept:\n pass")
0.3645319938659668

Ok, that is an expensive move. It could be the time for the dictionary to be created, taking a toll here.

Lets try an If statement

1
2
timeit.timeit(setup="a={k:k  for k in range(10000)}",stmt="if 10001 in a:\n b=a[10001]\nelse:\n pass")
0.048596858978271484

Ok, that’s much faster, so, I guess, no more try except blocks to find out key is present in the dictionary.

This post is licensed under CC BY 4.0 by the author.