Check if key exists in dictionary Python | Example code

Use Inbuilt method keys() to check if a key exists in dictionary Python. You can also use for in or has_key() method for it.

Example check given Key already exists in a Python Dictionary

Simple example code. The key() method returns a list of all the available keys in the dictionary. Once get the list of keys then use the if statement and the ‘in’ operator to check if the key exists in the dictionary or not.

def check_key(dict1, key):
    if key in dict1.keys():
        print("Exists , ", end=" ")
        print("value =", dict1[key])
    else:
        print("Not exists")


my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")

Output:

Check if key exists in dictionary Python

Another way using if and in

def check_key(dict1, key):
    if key in dict1:
        print("Exists")
    else:
        print("Not exists ")


my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")

Output: Exists

Using Inbuilt method has_key()

This method is used in older versions of Python.

def check_key(dict1, key):
    if dict1.has_key(key):
        print("Exists")
    else:
        print("Not exists ")


my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")

Output: It will throw an error.

AttributeError: ‘dict’ object has no attribute ‘has_key’

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

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.