This post will discuss how to check if a given key exists in a Python dictionary.

1. Using in operator

The preferred, the fastest way to check for the existence of a key in a dictionary is with the in operator. It returns True if the key is in the dictionary, False otherwise.

Download  Run Code

 
The in operator implement the built-in function __contains__. However, it is bad practice to call __contains__ directly. The in operator is a Pythonic way to invoke the __contains__ function.

Download  Run Code

2. Using dict.get() function

Another common approach to search for a key in a dictionary is using the get() function. This returns the key’s value if found; otherwise, the specified value or default value None is returned.

Download  Run Code

3. Using try/except block

You can also use the d[key] syntax to check for a key in a dictionary. This raises a KeyError when the specified key doesn’t exist in the dictionary. To handle it, use try/except block, as shown below:

Download  Run Code

4. Using setdefault() function

Finally, you can use the built-in function setdefault(), which inserts the key only if it is not found in the dictionary. This is particularly useful when you need to insert the key only if it doesn’t already exist in the dictionary.

Download  Run Code

That’s all about determining whether a given key exists in a Python dictionary.