How to use the get() method of a dictionary In Python

The get() method returns the value for a given key if it exists in the dictionary. If the key does not exist, it returns None. You can use this behavior to check if a value exists in the dictionary by checking if it is in the list returned by values().

Python3




test_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
if 21 in test_dict.values():
    print(f"Yes, It exists in dictionary")
else:
    print(f"No, It doesn't exist in dictionary")


Output

No, It doesn't exist in dictionary

Time complexity: O(n)
Auxiliary space: O(1)

Using isinstance() function:

Approach:

Check if the input value is of dictionary type or not.
If it is, check if the given element exists in any of the dictionary values.
If yes, return True. Else, return False.

Python3




def check_dict_value_1(d, val):
    if isinstance(d, dict):
        return any(val == v for v in d.values())
    return False
my_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, 'f': 5}
my_value = 4
result = check_dict_value_1(my_dict, my_value)
print(result)


Output

False

Time Complexity: O(n)
Auxiliary Space: O(1)



Python | Test if element is dictionary value

Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it’s any key’s value. This can have use cases in any field of programming one can think of. Let’s discuss certain ways in which this problem can be solved using Python

Similar Reads

Check if a value exists in the dictionary using any() function

This is the method by which this problem can be solved. In this, we iterate through the whole dictionary using list comprehension and check for each key’s values for a match using a conditional statement....

Check if a value exists in the dictionary using a loop

...

Check if a value exists in the dictionary using in operator and values()

This is the brute way in which this problem can be solved. In this, we iterate through the whole dictionary using loops and check for each key’s values for a match using a conditional statement....

Using the get() method of a dictionary

...

Contact Us