In [1]:
a = {f"{i}": i for i in range(10)}
a
Out[1]:
In [2]:
def handle_missing():
return 11
handle_missing()
Out[2]:
In [3]:
%%timeit
handle_missing()
In [4]:
%%timeit
a.get("11") or 11
In [5]:
%%timeit
a.get("11") or handle_missing()
In [6]:
%%timeit
a.get("11", 11)
In [7]:
%%timeit
a.get("11", handle_missing())
In [8]:
%%timeit
try:
a["11"]
except KeyError:
handle_missing()
In [9]:
%%timeit
if "11" in a:
a["11"]
else:
handle_missing()
In [10]:
def dynamic_handle_missing(key):
return int(key)
key = "11"
dynamic_handle_missing(key)
Out[10]:
In [11]:
%%timeit
dynamic_handle_missing(key)
In [12]:
%%timeit
a.get(key) or dynamic_handle_missing(key)
In [13]:
%%timeit
a.get(key, dynamic_handle_missing(key))
In [14]:
%%timeit
try:
a[key]
except KeyError:
dynamic_handle_missing(key)
In [15]:
%%timeit
if key in a:
a[key]
else:
dynamic_handle_missing(key)
In [ ]: