If key not in dictionary Python | Example code

Use the in operator to check if the key is not in the dictionary Python. Or you can use the get() method to check if the key exists.

Note: has_keys() method has been removed from the Python3 version. Therefore, it can be used in Python2 only.

Example If key not in dictionary Python

Simple example code.

Using the in operator

This operator is used to check if one value is a member of another. It returns a boolean value.

dict_1 = {"a": 1, "b": 2, "c": 3}

if "a" in dict_1:
    print("Does not exist")


If key not in dictionary Python

Similarly, the not in the operator can also be used to check if a key does not exist in a dictionary.

dict_1 = {"a": 1, "b": 2, "c": 3}

if "e" not in dict_1:
    print("Key e does not exist")

Output: Key e does not exist

Do comment if you have any doubts and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.