The Wayback Machine - https://web.archive.org/web/20241120014211/https://www.geeksforgeeks.org/python-test-if-element-is-dictionary-value/
Open In App

Python | Test if element is dictionary value

Last Updated : 17 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 min read
Python Program to Remove Nth element from Kth key's value from the dictionary
Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
9 min read
Python - Element Frequency starting with K in dictionary value List
Sometimes while working with a lots of data, we can have a problem in which we have data in form of strings list which are values of dictionary keys and we wish to count occurrences of elements starting with character K. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + startswith() This is one way in which thi
5 min read
Python - Sort dictionary by max/min element in value list
Given dictionary, perform sort on basis of maximum or minimum element present in dictionary values list. Input : test_dict = {"Gfg" : [6, 4], "best" : [8, 4], "for" : [7, 13], "geeks" : [15, 5]} Output : {'geeks': [15, 5], 'for': [7, 13], 'best': [8, 4], 'Gfg': [6, 4]} Explanation : Max of values is 15, occurs in "geeks" key, hence at 1st position
4 min read
Python - Key with Maximum element at Kth index in Dictionary Value List
Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list. Input : test_dict = {'Gfg' : [4, 6, 8, 2], 'is' : [1, 4, 5, 9], 'best' :[2, 3, 4, 10], 'for' :[4, 5, 2, 1], 'geeks' :[2, 10, 1, 8]}, K = 3 Output : best Explanation : 2, 9, 1
8 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Regular Dictionary vs Ordered Dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds key: value pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type does not track the insertion order of the (key, va
5 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done in Python. Example Converting dictionary string to dictionary using json
4 min read
Sort Python Dictionary by Key or Value - Python
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by keys and the result type will be a dictionary. [
6 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python | Test if key exists in tuple keys dictionary
Sometimes, while working with dictionary data, we need to check if a particular key is present in the dictionary. If keys are elementary, the solution to a problem in discussed and easier to solve. But sometimes, we can have a tuple as key of the dictionary. Let's discuss certain ways in which this task can be performed. Method #1 : Using any() + g
7 min read
Practice Tags :
three90RightbarBannerImg