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?
To get the value for the key, use dict[key] . dict[key] raises an error when the key does not exist, but the get() method returns a specified value (default is None ) if the key does not exist.
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
The “in” Keyword When querying a dictionary, the keys, and not the values, are searched.
If the situations with missing values are really exceptional then the exception handling is appropriate:
try:
value = my_dict[key]
# Do something
except KeyError:
pass
If both missing and present keys are to be handled then your first option is useful.
if key in my_dict:
value = my_dict[key]
# Do something
The use of get
doesn't provide any advantage in this specific situation. In contrary, you have to find a non-conflicting value to identify the missing key condition.
As mentioned several times, exception handling is the way to go. However, if you want to use get
and None
is a possible value, create a new object to act as the "not found" sentinel. (Since you've just created the object, it's impossible for it to be a valid entry in your dict
. Well, not impossible, but you would really have to go out of your way to add it to the dict
.)
sentinel = object()
value = my_dict.get(key, sentinel)
if value is not sentinel:
# Do something with value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With