I recently discovered something unexpected. Given a dict d that does not contain the key k , using a three-dimensional operator to try to get the default return item:
>>> def tern(): ... d[k] if k in d else 'foo' ... >>> timeit.timeit(tern, number=1000000) 0.12342095375061035
faster than dict .get() function:
>>> def get_meth(): ... d.get(k, 'foo') ... >>> timeit.timeit(get_meth, number=1000000) 0.20549297332763672
It seems intriguing to me. I would think that the ternary operator would require 2 searches via dict (once to check k in d ), then another to get d[k] , while .get would just try to extract d[k] , and if it fails, return 'foo' .
I used this for both the large dict (one million elements) and the small (100), and both times the triple was significantly faster. What is going on behind the scenes here?
source share