Open In App

Python | Test if element is dictionary value

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

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. 

Python3




test_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
# Check if key exist in dictionary using any()
if any([True for k,v in test_dict.items() if v == 21]):
    print(f"Yes, It exists in dictionary")
else:
    print(f"No, It doesn't exists in dictionary")


Output

No, It doesn't exists in dictionary

Check if a value exists in the dictionary using a loop 

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. 

Python3




# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Test if element is dictionary value
# Using loops
res = False
for key in test_dict:
    if(test_dict[key] == 3):
        res = True
        break
 
# printing result
print("Is 3 present in dictionary : " + str(res))


Output :

The original dictionary is : {'best': 3, 'is': 2, 'gfg': 1}
Is 3 present in dictionary : True

Time complexity: O(N), where N is the number of key-value pairs in the dictionary. 
Auxiliary space: O(1).

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

This task can be performed by utilizing the above functionalities. The in operator can be used to get the true value of presence and the values function is required to extract all values of dictionaries. 

Python3




# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Test if element is dictionary value
# Using in operator and values()
res = 3 in test_dict.values()
 
# printing result
print("Is 3 present in dictionary : " + str(res))


Output :

The original dictionary is : {'best': 3, 'is': 2, 'gfg': 1}
Is 3 present in dictionary : True

Time Complexity: O(n), where n is the number of values in the dictionary test_dict. 

Auxiliary Space: O(1), as no extra space is used.

Using the get() method of a dictionary

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)



Previous Article
Next Article

Similar Reads

Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python | Least Value test in Dictionary
While working with dictionary, we might come to a problem in which we require to ensure that all the values are atleast K in dictionary. This kind of problem can occur while checking status of start or checking for a bug/action that could have occurred. Let’s discuss certain ways in which this task can be performed. Method #1 : Using all() + dictio
7 min read
Python - Test Boolean Value of Dictionary
Sometimes, while working with data, we have a problem in which we need to accept or reject a dictionary on the basis of its true value, i.e all the keys are Boolean true or not. This kind of problem has possible applications in data preprocessing domains. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is
9 min read
Python - Test Kth index in Dictionary value list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if, throughout the dictionary, the kth index of all values in the dictionary is equal to N. This kind of problem can occur in the web development domain. Let's discuss certain ways in which this problem can be solved. Input : test_dict = {'Gfg' : [10,
9 min read
Python - Test for Empty Dictionary Value List
Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() + values() The combination of above functions can b
6 min read
Python - Test if element is part of dictionary
Given a dictionary, test if K is part of keys or values of dictionary. Input : test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2}, K = "Best" Output : True Explanation : "Best" is present in Dictionary as Key. Input : test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2}, K = "Geeks" Output : False Explanation : "Geeks" is not present in Dictionary as Key. Meth
6 min read
Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its corresponding "is" value is 11. Input : test_list = [{"Gfg" :
9 min read
Practice Tags :