Dictionary handle missing


In [1]:
a = {f"{i}": i for i in range(10)}
a


Out[1]:
{'0': 0,
 '1': 1,
 '2': 2,
 '3': 3,
 '4': 4,
 '5': 5,
 '6': 6,
 '7': 7,
 '8': 8,
 '9': 9}

In [2]:
def handle_missing():
    return 11
handle_missing()


Out[2]:
11

In [3]:
%%timeit
handle_missing()


68.8 ns ± 1.94 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [4]:
%%timeit 
a.get("11") or 11


119 ns ± 3.45 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [5]:
%%timeit 
a.get("11") or handle_missing()


192 ns ± 6.18 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [6]:
%%timeit 
a.get("11", 11)


123 ns ± 5.15 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [7]:
%%timeit 
a.get("11", handle_missing())


185 ns ± 10.8 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [8]:
%%timeit 
try:
    a["11"]
except KeyError:
    handle_missing()


360 ns ± 33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [9]:
%%timeit 
if "11" in a:
    a["11"]
else:
    handle_missing()


119 ns ± 9.23 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [10]:
def dynamic_handle_missing(key):
    return int(key)
key = "11"
dynamic_handle_missing(key)


Out[10]:
11

In [11]:
%%timeit
dynamic_handle_missing(key)


278 ns ± 6.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [12]:
%%timeit 
a.get(key) or dynamic_handle_missing(key)


414 ns ± 7.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [13]:
%%timeit 
a.get(key, dynamic_handle_missing(key))


416 ns ± 9.55 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [14]:
%%timeit 
try:
    a[key]
except KeyError:
    dynamic_handle_missing(key)


556 ns ± 15.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [15]:
%%timeit 
if key in a:
    a[key]
else:
    dynamic_handle_missing(key)


337 ns ± 37.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [ ]: