Delgan
Delgan

Reputation: 19617

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?

Upvotes: 8

Views: 21555

Answers (3)

Emmy R
Emmy R

Reputation: 132

if (dict.get('key') is not None) and ('key' in dict):
    var = dict['key']

Second portion of if-statement may not be totally necessary but I have used this format in my own code and it does the job.

Upvotes: 1

chepner
chepner

Reputation: 531055

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

Upvotes: 2

dlask
dlask

Reputation: 8982

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.

Upvotes: 9

Related Questions