Check if key in dictionary Python | Example code

Using the in operator with if statement to check if a key exists in dictionary python. These methods are the Inbuilt methods.

Example check if key in dictionary Python

Simple Python program to check whether a given key already exists in a dictionary.

dict_1 = {"a": 1, "b": 2, "c": 3}
if "a" in dict_1:
    print("Exists")
else:
    print("Does not exist")

Output:

Check if key in dictionary Python

Another method using Inbuilt method keys()

def check_key(d, key):
    if key in d.keys():
        print("Present, ", end=" ")
        print("value =", d[key])
    else:
        print("Not present")


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

Output: Present, value = 1

Do comment if you have any doubts and suggestions on this Python dict tutorial.

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.