Python – Check for Key in Dictionary Value list
Last Updated :
15 May, 2023
Sometimes, while working with data, we might have a problem we receive a dictionary whose whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let’s discuss certain ways in which this task can be performed.
Method #1: Using any()
This is the simple and most recommended way in which this task can be performed. In this, we just check for the key inside the values by iteration.
Approach:
- The program starts by initializing a dictionary named test_dict that contains three key-value pairs.
- The first key-value pair is ‘Gfg’ : [{‘CS’ : 5}, {‘GATE’ : 6}], where the key is a string ‘Gfg’ and the value is a list of two dictionaries {‘CS’ : 5} and {‘GATE’ : 6}.
- The second key-value pair is ‘for’ : 2, where the key is a string ‘for’ and the value is an integer 2.
- The third key-value pair is ‘CS’ : 3, where the key is a string ‘CS’ and the value is an integer 3.
- Next, the program prints the original dictionary using the print() function.
- The program then initializes a string variable named key with the value “GATE”.
- The program checks if the given key “GATE” exists in the list of dictionaries associated with the key “Gfg”.
- This is done using the any() function which checks if the given condition is True for at least one element of an iterable. Here, the iterable is the list of dictionaries associated with the key “Gfg”, and the condition being checked is if the key “GATE” exists in any of these dictionaries. The result of this check is stored in the boolean variable res.
- Finally, the program prints the result of the check by converting the boolean variable res to a string using the str() function and concatenating it with a string.
Python3
test_dict = { 'Gfg' : [{ 'CS' : 5 }, { 'GATE' : 6 }], 'for' : 2 , 'CS' : 3 }
print ( "The original dictionary is : " + str (test_dict))
key = "GATE"
res = any (key in ele for ele in test_dict[ 'Gfg' ])
print ( "Is key present in nested dictionary list ? : " + str (res))
|
Output
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True
Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required
Method #2: Using list comprehension + in operator
The combination of the above functionalities can be used to perform this task. In this, we iterate through the list using comprehension and perform key flattening and store keys. Then we check for the desired key using in operator.
Python3
test_dict = { 'Gfg' : [{ 'CS' : 5 }, { 'GATE' : 6 }], 'for' : 2 , 'CS' : 3 }
print ( "The original dictionary is : " + str (test_dict))
key = "GATE"
res = key in [sub for ele in test_dict[ 'Gfg' ] for sub in ele.keys()]
print ( "Is key present in nested dictionary list ? : " + str (res))
|
Output
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: Using loop
Approach:
- Initialize the dictionary test_dict and the key to be searched in the dictionary value list.
- Initialize a Boolean variable res to False.
- Loop through the value list of the dictionary key ‘Gfg’ using for loop.
- Check if the key is present in the sub-dictionary using if statement and the keys() method.
- If the key is present in the sub-dictionary, set the res variable to True and break the loop.
- Print the result.
Python3
test_dict = { 'Gfg' : [{ 'CS' : 5 }, { 'GATE' : 6 }], 'for' : 2 , 'CS' : 3 }
print ( "The original dictionary is : " + str (test_dict))
key = "GATE"
res = False
for ele in test_dict[ 'Gfg' ]:
if key in ele.keys():
res = True
break
print ( "Is key present in nested dictionary list ? : " + str (res))
|
Output
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True
Time complexity: O(n), where n is the number of elements in the value list of the dictionary key ‘Gfg’.
Auxiliary space: O(1), as we are using constant space for the Boolean variable res.
Method #4: Using set() and intersection() functions
The combination of the above functionalities can be used to perform this task. In this, we create a set with only the key and use the set() and intersection() functions to find common elements between this set and each dictionary value list. If there is at least one common element, then the key exists in the corresponding value list.
Python3
test_dict = { 'Gfg' : [{ 'CS' : 5 }, { 'GATE' : 6 }], 'for' : 2 , 'CS' : 3 }
print ( "The original dictionary is : " + str (test_dict))
key = "GATE"
res = bool ( set (test_dict[ 'Gfg' ][ 1 ].keys()).intersection([key]))
print ( "Is key present in nested dictionary list ? : " + str (res))
|
Output
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True
Time complexity: O(n), where n is the number of keys in the nested dictionaries.
Auxiliary space: O(1), it uses constant memory
Similar Reads
Python | Check if key has Non-None value in dictionary
Sometimes, while working with Python dictionaries, we might come across a problem in which we need to find if a particular key of the dictionary is valid i.e it is not False or has a non-none value. This kind of problem can occur in the Machine Learning domain. Let's discuss certain ways in which th
6 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Check if all values are K in dictionary
While working with dictionary, we might come to a problem in which we require to ensure that all the values are K in dictionary. This kind of problem can occur while checking the status of the start or checking for a bug/action that could have occurred. Letâs discuss certain ways in which this task
9 min read
Check if Value Exists in Python Dictionary
Dictionaries in Python offer a powerful way to store and retrieve data through key-value pairs. As developers, frequently, we encounter scenarios where we need to determine whether a specific value exists within a dictionary. In this article, we will explore commonly used methods to perform this tas
4 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Letâs discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops
10 min read
Python - Filter dictionaries by values in Kth Key in list
Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Minimum Value Keys in Dictionary - Python
We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
4 min read
Check if dictionary is empty in Python
Sometimes, we need to check if a particular dictionary is empty or not. [GFGTABS] Python # initializing empty dictionary d = {} print(bool(d)) print(not bool(d)) d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(bool(d)) print(not bool(d)) [/GFGTABS]OutputFalse True True False Dif
5 min read