Skip to content

Instantly share code, notes, and snippets.

@5j9
Last active August 6, 2018 04:52
Show Gist options
  • Save 5j9/932c006c4ce8c45a51ed2032163db294 to your computer and use it in GitHub Desktop.
Save 5j9/932c006c4ce8c45a51ed2032163db294 to your computer and use it in GitHub Desktop.
Comparing different nested dictionary access methods; 50% key availablity
from timeit import *
try_method = '''
try:
d[1][2]
except KeyError:
pass
'''
get_method = 'd.get(1, {}).get(2, {})'
if_method = '''
if 1 in d and 2 in d[1]:
d[1][2]
'''
get_if_method = '''
v1 = d.get(1)
if v1:
v2=d.get(2)
if v2:
d[1][2]
'''
# Assuming the keys exists 50%
print(min(repeat(if_method, 'd={1:{2:{3:3}}}')) + min(repeat(if_method, 'd={}')))
print(min(repeat(get_if_method, 'd={1:{2:{3:3}}}')) + min(repeat(get_if_method, 'd={}')))
print(min(repeat(try_method, 'd={1:{2:{3:3}}}')) + min(repeat(try_method, 'd={}')))
print(min(repeat(get_method , 'd={1:{2:{3:3}}}')) + min(repeat(get_method, 'd={}')))
# Python 3.7 x64 Win
# 0.12123334500000008
# 0.1651155179999998
# 0.2357646899999999
# 0.3231400500000001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment