How to check if a key exists in a dictionary in python?

Dictionary is a built-in datatype in python that stores the collection of data as key-value pairs. The key-value pairs in the dictionary are enclosed within curly brackets {}. Dict_1 = {1: "one", 2: "two", 5: "five"} represents a dictionary.

This article discusses different approaches to check the existence of a key in a dictionary.

Checking the existence of a key by using the keys() method and in operator

The keys() function return a list of keys present in the dictionary. The keys() function doesn't take any argument. The syntax for the keys() function is as follows.

#syntax:
dict.keys()

The in operator checks the existence of the key in the list of dict_keys and returns a boolean value True or False as output. For example, Consider a dictionary Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}. The below code checks if key 2 is present in Dict_1.

Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}
print("List of keys : ", Dict_1.keys())
if 2 in Dict_1.keys():
    print("2 is present")
else:
    print("Not present")

The above code gives output as

List of keys :  dict_keys([1, 2, 3, 'color'])
2 is present

Checking the existence of a key by using if statement and in operator

The in operator checks the existence of the key in the dictionary and returns a boolean value True or False as output. Consider a dictionary Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}. The below code checks if key "color" is present in Dict_1.

If the key is found in the dictionary if block is executed. If the key doesn't exist in the dictionary, statements inside the else block are executed and the output is printed.

Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}
print("Dict_1 : ", Dict_1)
if "color" in Dict_1:
    print("Key Found")
else:
    print("Not Found")

The above code returns the output as

Dict_1 :  {1: 'apple', 2: 'orange', 3: 'grapes', 'color': 'red'}
Key Found

Checking the existence of a key by using for loop

Consider a dictionary Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}. A variable flag is initialized to 0. A for loop iterates over the dictionary and checks the existence of the key "color" in Dict_1.

If the key is found if block is executed, the variable flag is initialized to 1 and the output is printed. If the variable flag remains 0, this indicates that the key is not found in Dict_1.

Dict_1 = {1: "apple", 2: "orange", 3:"grapes", "color": "red"}
print("Dict_1 : ", Dict_1)
flag = 0
for key in Dict_1:
    if key == "color":
        print("Key Found")
        flag =1
        break
if flag == 0:
    print("Key Not Found")

The above code returns the output as

Dict_1 :  {1: 'apple', 2: 'orange', 3: 'grapes', 'color': 'red'}
Key Found
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions