Open In App

Python – Extract Key’s Value, if Key Present in List and Dictionary

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

Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary.

Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], 
                test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" 
Output : 5 
Explanation : "Gfg" is present in list and has value 5 in dictionary. 

Input : test_list = ["Good", "for", "Geeks"], 
                test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" 
Output : None 
Explanation : "Gfg" not present in List.

Method #1 : Using all() + generator expression

The combination of the above functions offers one of the ways in which this problem can be solved. In this, we use all() to check for occurrence in both dictionary and list. If the result is true value is extracted from to result.

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using all() + list comprehension
 
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
# using all() to check for occurrence in list and dict
# encapsulating list and dictionary keys in list
res = None
if all(K in sub for sub in [test_dict, test_list]):
    res = test_dict[K]
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

Time complexity: O(n), where n is the total number of elements in the test_list. This is because, in the worst case, each element of the list needs to be checked for its presence in both the list and the dictionary, resulting in a time complexity of O(n).
Auxiliary space: O(1), as it only requires a constant amount of additional memory to store the result and temporary variables.

Method #2 : Using set() + intersection()

This is another way to check for the key’s presence in both containers. In this, we compute the intersection of all values of list and dict keys and test for the Key’s occurrence in that.

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using set() + intersection()
 
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
# conversion of lists to set and intersection with keys
# using intersection
res = None
if K in set(test_list).intersection(test_dict):
    res = test_dict[K]
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(m), where m is the number of unique keys in the dictionary that match the elements in the list.

Method #3: Using in operator

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
 
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
if K in test_dict.keys() and K in test_list:
    res=test_dict[K]
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

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

Method 4: Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
import operator as op
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg": 2, "is": 4, "Best": 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
if op.countOf(test_dict.keys(), K) > 0 and op.countOf(test_list, K) > 0:
    res = test_dict[K]
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

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

Method 5: Using any() + dictionary.get() method

Step-by-step approach:

  • Use the any() function to check if the string variable K is present in both the test_list and test_dict.
  • If K is present in both test_list and test_dict, use the get() method of the dictionary to retrieve the value corresponding to the key K and store it in a variable named res.
  • Print the extracted value of K from the dictionary in a human-readable format by converting it to a string using the str() function, and concatenating it with a message string.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using any() + dictionary.get() method
 
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg": 2, "is": 4, "Best": 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
# using any() to check for occurrence in list and dict
# accessing value of key using dictionary.get() method
res = None
if K in test_list and K in test_dict:
    res = test_dict.get(K)
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

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

Method #6: Using try-except block to handle KeyErrors

Use a try-except block to handle the KeyError that may occur if K is not present in test_dict. First, check if K is present in both test_list and test_dict.keys(). If yes, extract the value of K from test_dict. If no, set the result to None. If a KeyError occurs, handle it by setting the result to None. Finally, print the result.

Python3




test_list = ["Gfg", "is", "Good", "for", "Geeks"]
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
K = "Gfg"
 
try:
    # check if K is present in both test_list and test_dict keys
    if K in test_list and K in test_dict.keys():
        # if yes, extract value of K from test_dict
        res = test_dict[K]
    else:
        # if no, set result to None
        res = None
except KeyError:
    # handle KeyError exception
    res = None
     
# print result
print("Extracted Value : " + str(res))


Output

Extracted Value : 2

Time complexity: O(n), where n is the length of the test_list. This is because we check if K is present in both test_list and test_dict.keys(), which takes O(n) time in the worst case.
Auxiliary space: O(1), because we use a constant amount of extra space to store the variables test_list, test_dict, K, and res, and we don’t create any additional data structures in the code.

Method #7: Using try-except block with .get() method

This method involves using a try-except block to check if the key exists in the dictionary and retrieve its value using the .get() method.

Follow the below steps to implement the above idea:

  • Initialize the list, dictionary, and key, same as in the original code.
  • Use a try-except block to handle the KeyError exception that occurs if the key is not found in the dictionary.
  • Inside the try block, retrieve the value of the key using the .get() method on the dictionary. If the key is not found, .get() will return None by default.
  • If the key is found in both the list and dictionary, return the value of the key. If not, return None.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using try-except block with .get() method
 
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
 
# initializing K
K = "Gfg"
 
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
 
# using try-except block with .get() method
res = None
try:
    if K in test_list and K in test_dict:
        res = test_dict.get(K)
except KeyError:
    pass
 
# printing result
print("Extracted Value : " + str(res))


Output

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

Time complexity: O(n), Where n is the length of test_list.
Auxiliary space: O(1) for storing the result and constant extra space for the try-except block.

Method #8: Using a for loop to iterate through the list and dictionary

Step-by-step approach:

  • Initialize the list, dictionary, and key as given in the problem statement:
  • Use a for loop to iterate through the list and dictionary:
    • Checks each item in the list. If an item is equal to the key, it uses the get() method to retrieve the corresponding value from the dictionary. 
    • If the key is not found, res is set to None. The loop stops as soon as a matching item is found.
  • Print the extracted value:

Python




test_list = ["Gfg", "is", "Good", "for", "Geeks"]
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
K = "Gfg"
 
# Method 9: Using a for loop to iterate through the list and dictionary
res = None
for item in test_list:
    if item == K:
        res = test_dict.get(K)
        break
 
print("Method 9: Extracted Value : " + str(res))


Output

Method 9: Extracted Value : 2

Time complexity: O(n), where n is the length of the list
Auxiliary space: O(1)

Method #9: Using numpy:

Algorithm:

  1. Import numpy module
  2. Initialize list, dictionary and key
  3. Use numpy’s isin() function to check if the key is present in both the list and dictionary
  4. If the key is present in both the list and dictionary, extract the value from the dictionary
  5. Print the extracted value

Python3




import numpy as np
 
 
# initializing list
 
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
 
 
# initializing Dictionary
 
test_dict = {"Gfg": 2, "is": 4, "Best": 6}
 
 
# initializing K
 
K = "Gfg"
 
 
# printing original list and Dictionary
 
print("The original list : " + str(test_list))
 
print("The original Dictionary : " + str(test_dict))
 
 
# Using numpy's isin() function to check if K is present in both the list and dictionary
 
if np.isin(K, test_list) and np.isin(K, np.array(list(test_dict.keys()))):
 
    res = test_dict[K]
 
 
# printing result
 
print("Extracted Value : " + str(res))
 
# This  code is contributed by Jyothi pinjala.


Output:

The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2

Time Complexity: O(n), where n is the length of the list and the number of keys in the dictionary. Both the isin() function and dictionary keys() function have a time complexity of O(n).
Auxiliary Space: O(n), where n is the length of the list and the number of keys in the dictionary. The isin() function creates a numpy array of length n, and the dictionary takes up space proportional to the number of keys.

Method#10: Using Recursive method.

Step-by-step approach:

  • Define a function extract_value that takes in three arguments: test_list, test_dict, and K.
  • Check if test_list is empty.
  • If test_list is empty, return None.
  • Otherwise, check if the first element of test_list is equal to K.
  • If the first element of test_list is equal to K, return the value associated with key K in test_dict using the get method.
  • Otherwise, call extract_value recursively with the remaining elements of test_list.

Below is the implementation of the above approach:

Python3




def extract_value(test_list, test_dict, K):
    if not test_list:
        return None
    elif test_list[0] == K:
        return test_dict.get(K)
    else:
        return extract_value(test_list[1:], test_dict, K)
 
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
K = "Gfg"
 
res = extract_value(test_list, test_dict, K)
print("Extracted Value : " + str(res))


Output

Extracted Value : 2

Time complexity: O(n), where n is the length of test_list. This is because we need to iterate over all elements of test_list to find the key K.
Auxiliary space: O(n), where n is the length of test_list. This is because we need to store n recursive calls on the call stack.



Similar Reads

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 program to find Maximum value from dictionary whose key is present in the list
Given a list with dictionary keys and a dictionary, extract maximum from dictionary values, whose key is present in list. Examples: Input : test_dict = {"Gfg": 4, "is" : 5, "best" : 10, "for" : 11, "geeks" : 3}, test_list = ["Gfg", "best", "geeks"] Output : 10 Explanation : Max value is 11, but not present in list, 10 is of key best, which is also
6 min read
Access a Dictionary Key Value Present Inside a List
The dictionary is a data structure in Python. A Dictionary in Python holds a key-value pair in it. Every key in the dictionary is unique. A value present in Dictionary can be accessed in Python in two different ways. A list can hold any data structure to it. A list can also contain a dictionary in it. In this article, we will see how to access a di
2 min read
Python | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in which this can be done. Method #1: Using items()
5 min read
Python program to extract key-value pairs with substring in a dictionary
Given a dictionary list, extract all the dictionaries which have substring present in particular key. Input : [{"Gfg" : "4", "best" : "1"}, {"Gfg" : "good CS content", "best" : "10"}], K = "Gfg", sub_str = "CS" Output : [{'Gfg': 'good CS content', 'best': '10'}] Explanation : "Gfg" has "CS" as substring value. Input : [{"Gfg" : "4", "best" : "1"},
7 min read
Extract Subset of Key-Value Pairs from Python Dictionary
In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filtering, transforming, or manipulating data. Extract S
4 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
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 - Extract Kth index elements from Dictionary Value list
Given a dictionary with list as values, extract all the Kth index elements. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 2 Output : [5, 7, 8] Explanation : The 2nd index elements are 5, 7 and 8 respectively in different keys. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 0 Output : [4, 8, 9] Explan
7 min read
Python program to extract the Unique Dictionary Value List elements
Given Dictionary with value lists, extract all unique values. Input : test_dict = {"Gfg" : [6, 7, 4, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 4, 8, 5, 2] Explanation : All distincts elements extracted. Input : test_dict = {"Gfg" : [6, 7, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 8, 5, 2] Explanation : All distincts elements extracted. Method #
6 min read