Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists and get the value at the same time in Python?

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?

like image 517
Delgan Avatar asked Jul 07 '15 19:07

Delgan


People also ask

How do you check if a key matches a value in Python?

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.

How do you check if a key exists in Python?

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.

How do you check if a key is present or not?

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.

What is the keyword that is used to check if a particular key exists in a dictionary?

The “in” Keyword When querying a dictionary, the keys, and not the values, are searched.


2 Answers

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.

like image 147
dlask Avatar answered Sep 20 '22 02:09

dlask


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
like image 38
chepner Avatar answered Sep 19 '22 02:09

chepner