Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Benchmark of get methods with python
from __future__ import print_function
a_dict = {x: str(x) for x in range(1000)}
def with_get():
result1 = a_dict.get(-1, None)
result2 = a_dict.get(900, None)
def with_exception():
result1 = a_dict[-1]
except KeyError:
result1 = None
result2 = a_dict[900]
except KeyError:
result2 = None
def with_in():
result1 = a_dict[-1] if -1 in a_dict else None
result2 = a_dict[900] if 900 in a_dict else None
if __name__ == '__main__':
import timeit
import sys
using_get = timeit.Timer('with_get()', 'from __main__ import with_get')
using_exception = timeit.Timer('with_exception()', 'from __main__ import with_exception')
using_in = timeit.Timer('with_in()', 'from __main__ import with_in')
print('with_get(): ', using_get.timeit())
print('with_exception():', using_exception.timeit())
print('with_in(): ', using_in.timeit())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.