While reading Python 101 by Michael Driscoll I got to his explanation on checking if a key exists in a dictionary. I checked it on my machine with a dictionary containing keys 'a' to 'z' where the value is their order, and a function that measures time on retrieving the key 't' (picked it at random)
Here's my function:
def f(d, flag):
start_time = time.time()
if flag:
print("t" in d)
else:
print("t" in d.keys())
print("--- %s seconds ---" % (time.time() - start_time))
And here are the results:
>>> f(dict,True)
True
--- 0.03937530517578125 seconds ---
>>> f(dict,False)
True
--- 0.05114388465881348 seconds ---
BUT, I still don't get it. I thought that key in dict.keys() would result in iteration on much smaller collection, which will be faster. Is there something special in the implementation of in or keys() that causes this?