How to check if a value is in a dictionary in python?

A dictionary is a collection of key-value pairs that are ordered, mutable, and doesn't allow redundant data. Dictionaries are written with curly brackets {}. Dict_1 = {1: "one", 2: "two", 5: "five"} represents a dictionary.

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

Checking the existence of a value by using the values() method and in operator

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

#syntax
dictionary.values()

The in operator checks the existence of the value in the list of dict_values and returns a boolean value True or False as output.

For example, Consider a dictionary dict_1 = {1: "one", 2: "two", 3: "three"}. The below code checks if the value "two" is present in a dict_1.

dict_1 = {1: "one", 2: "two", 3: "three"}
print("dict_1 : ", dict_1)
if "two" in dict_1.values():
    print("Value found")
else:
    print("Value not found")

The code gives output as

dict_1 :  {1: 'one', 2: 'two', 3: 'three'}
Value found

Checking the existence of a value by using for loop

Let us consider a dictionary dict_1 = {1: "one", 2: "two", 3: "three"}. The variable flag is initialized to value 0. A for loop iterates over the dictionary and checks if the value "four" is present in the dictionary. If the value is found if block is executed and the variable flag is assigned to value 1.

If the value of the flag variable remains 0, it indicates the value is not in the dictionary.

dict_1 = {1: "one", 2: "two", 3: "three"}
print("dict_1 : ", dict_1)
flag = 0
for key in dict_1:
    if dict_1[key] == "four":
        flag = 1
        print("Value found")
        break
if flag == 0:
    print("Value not found")

The above program returns the output as

dict_1 :  {1: 'one', 2: 'two', 3: 'three'}
Value not found
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions