Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Check for Key in Dictionary Value list

Python – Check for Key in Dictionary Value list

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:

  1. The program starts by initializing a dictionary named test_dict that contains three key-value pairs.
  2. 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}.
  3. The second key-value pair is ‘for’ : 2, where the key is a string ‘for’ and the value is an integer 2.
  4. The third key-value pair is ‘CS’ : 3, where the key is a string ‘CS’ and the value is an integer 3.
  5. Next, the program prints the original dictionary using the print() function.
  6. The program then initializes a string variable named key with the value “GATE”.
  7. The program checks if the given key “GATE” exists in the list of dictionaries associated with the key “Gfg”.
  8. 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.
  9. 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




# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using any()
 
# Initializing dictionary
test_dict = {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initializing key
key = "GATE"
 
# Check for Key in Dictionary Value list
# Using any()
res = any(key in ele for ele in test_dict['Gfg'])
 
# Printing result
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




# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using list comprehension + in operator
 
# Initializing dictionary
test_dict = {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initializing key
key = "GATE"
 
# Checking for Key in Dictionary Value list
# Using list comprehension + in operator
res = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys()]
 
# Printing result
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:

  1. Initialize the dictionary test_dict and the key to be searched in the dictionary value list.
  2. Initialize a Boolean variable res to False.
  3. Loop through the value list of the dictionary key ‘Gfg’ using for loop.
  4. Check if the key is present in the sub-dictionary using if statement and the keys() method.
  5. If the key is present in the sub-dictionary, set the res variable to True and break the loop.
  6. Print the result.

Python3




# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using loop
 
# initializing dictionary
test_dict = {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing key
key = "GATE"
 
# Check for Key in Dictionary Value list
# Using loop
res = False
for ele in test_dict['Gfg']:
    if key in ele.keys():
        res = True
        break
 
# printing result 
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




# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using set() and intersection()
 
# Initializing dictionary
test_dict = {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initializing key
key = "GATE"
 
# Check for Key in Dictionary Value list
# using set() and intersection()
res = bool(set(test_dict['Gfg'][1].keys()).intersection([key]))
 
# Printing result
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

RELATED ARTICLES

Most Popular

Recent Comments