So I have to search if a key is present in dictionary or not. From this post: here
I can see that the intended way to check for this is using:
if key in dict
but my questions is, would it would be better to do this:
def appendToMyDict(key, value):
try:
old_value = dict[key]
newValue = old_value + value
dict[key] = newValue
except KeyError:
dict[key] = value
My intention is to optimize "getting the key" as much as I can, because my key space will be very large, around 1000 or above.
The way I see it is that dictionaries are hashmaps. So when I do dict[key], python would be hashing the key, and would have been getting its value in O(1) time. But while searching for the key using the "if key in dict" method, it will be take time O(n)[Because it will searching through the whole key space].
But if I throw error, it would take time of O(1) + time to throw and catch the error.
Am I correct ?