"One semi-gotcha to avoid though is to make sure you do: key in some_dict
rather than key in some_dict.keys()
. Both are equivalent semantically, but performance-wise the latter is much slower (O(n) vs O(1)). I've seen people do the in dict.keys()
thinking it's more explicit & therefore better."
I found this piece of advice online. Can anyone please explain and justify the above difference in performance? How is the working of these two seemingly similar statements so different?
EDIT: To be more precise, how is indexing in a dictionary faster than indexing in a list? As far as I've learned, hash tables are arrays of linked lists. The array being an array of the keys. So finding a key in a hash table should be similar to finding that key in a list of keys. (?)