Skip to content

Check if key in dictionary Python | Example code

  • by

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("Does not exist")


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])
        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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *