Both of these operations do the same thing: consider the hash table implemented in the dict for the key. There will be no iteration of the entire dictionary. Keep in mind that for x in dict is different from if x in dict . They use the in keyword, but perform different operations.
The in keyword becomes a call to dict.__contains__ , which dict can implement, but he likes.
If there is a difference in the timings of these operations, it will be very small and will be associated with the service overlay of the has_key function.
By the way, the general preference for key in dict is a clearer expression of intent than dict.has_key(key) . Note that speed has nothing to do with preference. Readability is more important than speed if you do not know that you are on a critical path.
source share