Sometimes we may need to verify the existence of a key in a dictionary and make something if the corresponding value exists.
Usually, I proceed in this way:
if key in my_dict:
value = my_dict[key]
# Do something
This is of course highly readable and quick, but from a logical point of view, it bothers me because the same action is performed twice in succession. It's a waste of time.
Of course, access to the value in the dictionary is amortized and is normally instantaneous. But what if this is not the case, and that we need to repeat it many times?
The first workaround I thought to was to use .get()
and check if the returned value is not the default one.
value = my_dict.get(key, default=None)
if value is not None:
# Do Something
Unfortunately, this is not very practical and it can cause problems if the key exists and its corresponding value is precisely None
.
Another approach would be to use a try
/ except
block.
try:
value = my_dict[key]
# Do something
except KeyError:
pass
However, I highly doubt this is the best of ways.
Is there any other solution which is unknown to me, or should I continue using the traditional method?