Check if key exists in Python dictionary

0
8663
Check if key exists in Python dictionary

This is supposed to be an easy task but in reality it looks like lots of Python developers have trouble with it; especially, who are new to Python. I will show you several ways to check if key exists in Python dictionary.

Check if key exists in Python dictionary

In Python, dictionary is a mapping object that can store data like a hash table, and it is the only builtins mapping type.

To get value of a given key, we use d[key], assuming that d is a dictionary.

If key doesn’t exist in d, Python will throw a KeyError.

To fix this, we need to check if key existence before querying it. Following are three ways to check it.

Let’s start with following dictionary:

article = {
  'title': 'Check if key exists in Python dictionary',
  'author': 'Pete Houston',
  'year' : 2019
}

1. Use key in dict

The expression returns Boolean value, so combining with one line condition syntax will make it pretty convenient to write.

author = article['author'] if 'author' in article else 'Pete Houston'

With else statement we can also provide the fallback value in case the key doesn’t exist in dictionary. It looks pretty good to use.

However, it requires a bit more typing. Well, try the next method.

2. Use get()

There is one problem with first method is that, so many examples and tutorials introducing Python uses key in dict ; therefore, it makes key in dict syntax so popular, and developers forget or don’t know about the get() function, which is written so clear in Python’s official documentation.

get(key[, default])
    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

So we can write like this:

title = article.get('title', 'Default Title')

The default parameter is optional, and it returns None if key not found. The doc states it pretty clear.

Using get() sounds a better choice than using key in dict .

3. The internal extra function

This is an internal function inside dictionary, __contains__.

You can use this function to verify key existence, too.

year = article['year'] if article.__contains__('year') else date.today().year
NOTE: As you know, this is internal function; hence, it will be removed any time. Don’t use it on production!

Conclusion

Now you know how to check if key exists in Python dictionary. Don’t forget!