Open In App

Python – Extract dictionary items with List elements

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let’s discuss certain ways in which this task can be performed.
 

Input : test_dict = {‘gfg’ : [4, 6, 10], ‘is’ : [12]} 
Output : {‘gfg’: [4, 6, 10]}

Input : test_dict = {‘gfg’ : [4, 6, 10]} 
Output : {‘gfg’: [4, 6, 10]} 

Method #1 : Using set() + dictionary comprehension + items() 
The combination of above functionalities can be used to solve this problem. In this, we first reduce the list elements to remove duplicate, extract dictionary items using items() and construction of required dictionary happens using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Extract dictionary items with List elements
# Using set() + dictionary comprehension + items()
 
# helpr_fnc
def hlper_fnc(req_list, test_dict):
    temp = set(req_list)
    temp2 = { key: set(val) for key, val in test_dict.items() }
    return { key: val for key, val in test_dict.items() if temp2[key].issubset(temp)}
 
# initializing dictionary
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing req_list
req_list = [4, 6, 10]
 
# Extract dictionary items with List elements
# Using set() + dictionary comprehension + items()
res = hlper_fnc(req_list, test_dict)
     
# printing result
print("The extracted dictionary: " + str(res))


Output : 
The original dictionary : {‘is’: [10], ‘best’: [4, 5, 7], ‘gfg’: [4, 6]} 
The extracted dictionary: {‘is’: [10], ‘gfg’: [4, 6]} 
 

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

Method #2 : Using all() + dictionary comprehension 
The combination of above functions can be used to solve this problem. This is one-liner solution and uses all() to check for elements membership to decide for filtration. The dictionary comprehension performs task of construction of dictionary.

Python3




# Python3 code to demonstrate working of
# Extract dictionary items with List elements
# Using all() + dictionary comprehension
 
# initializing dictionary
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing req_list
req_list = [4, 6, 10]
 
# Extract dictionary items with List elements
# Using all() + dictionary comprehension
res = {key: val for key, val in test_dict.items() if all(vals in req_list for vals in val)}
     
# printing result
print("The extracted dictionary: " + str(res))


Output : 

The original dictionary : {'is': [10], 'best': [4, 5, 7], 'gfg': [4, 6]}
The extracted dictionary: {'is': [10], 'gfg': [4, 6]}

 

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #3: Using set intersection + dictionary comprehension

  • Define a function named extract_dict that takes two parameters, req_list and test_dict.
  • Convert req_list to a set named set_req_list.
  • Create a dictionary comprehension that iterates over the items of test_dict and filters out the items whose value set is not a subset of set_req_list.
  • Return the resulting dictionary.
  • Call the extract_dict function with req_list and test_dict as arguments.
  • Print the original dictionary and the extracted dictionary.

Python3




# Python3 code to demonstrate working of
# Extract dictionary items with List elements
# Using set intersection + dictionary comprehension
 
# Define function to extract dictionary items
def extract_dict(req_list, test_dict):
    set_req_list = set(req_list)
    return {k:v for k,v in test_dict.items() if set(v).issubset(set_req_list)}
 
# initialize dictionary
test_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]}
 
# print original dictionary
print("The original dictionary: " + str(test_dict))
 
# initialize required list
req_list = [4, 6, 10]
 
# extract dictionary items with list elements
res = extract_dict(req_list, test_dict)
 
# print extracted dictionary
print("The extracted dictionary: " + str(res))


Output

The original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}

Time complexity: O(n*m), where n is the number of items in test_dict and m is the maximum length of the value list in test_dict. This is because we iterate over the items of test_dict and then over the items of the value list.
Auxiliary space: O(k), where k is the number of items in the resulting dictionary. We store the resulting dictionary in memory.

Method 4: Using for loop and conditional statements

  • We define a helper function called extract_dict_items that takes two arguments req_list and test_dict.
  • We initialize an empty dictionary called result_dict to store the key-value pairs that meet our condition.
  • We iterate through the key-value pairs of the dictionary using a for loop.
  • For each key-value pair, we check if all the items in the value list are also in the req_list using the all() function and a conditional statement.
  • If the condition is True, we add the key-value pair to the result_dict.
  • After iterating through all the key-value pairs, we return the result_dict.
  • Finally, we call the extract_dict_items() function with the req_list and test_dict arguments, and print the original and extracted dictionaries.

Python3




# helper function
def extract_dict_items(req_list, test_dict):
    result_dict = {}
    for key, val in test_dict.items():
        if all(item in req_list for item in val):
            result_dict[key] = val
    return result_dict
 
# initializing dictionary
test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
 
# printing original dictionary
print("The original dictionary: " + str(test_dict))
 
# initializing req_list
req_list = [4, 6, 10]
 
# Extract dictionary items with List elements using for loop and conditional statements
res = extract_dict_items(req_list, test_dict)
 
# printing result
print("The extracted dictionary: " + str(res))


Output

The original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}

Time complexity: O(n*m), where n is the number of key-value pairs in the dictionary, and m is the maximum length of the value lists.
Auxiliary space: O(k), where k is the number of key-value pairs that meet the condition.

Method #5: Using filter() and lambda function

In this method, we can use the built-in function filter() along with a lambda function to filter out the dictionary items that meet the criteria. Here’s the step-by-step approach:

  1. Define a lambda function that takes in a key-value pair of the dictionary and returns True if all the values in the list associated with the key are present in the req_list, else False.
  2. Use the filter() function to filter out the key-value pairs that meet the criteria defined in the lambda function.
  3. Convert the filtered items into a dictionary using the dict() function.

Python3




# initializing dictionary
test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
 
# printing original dictionary
print("The original dictionary: " + str(test_dict))
 
# initializing req_list
req_list = [4, 6, 10]
 
# define the lambda function
is_subset = lambda key_val: all(val in req_list for val in key_val[1])
 
# use the filter function to filter out the key-value pairs that meet the criteria
filtered_items = filter(is_subset, test_dict.items())
 
# convert the filtered items into a dictionary
res = dict(filtered_items)
 
# printing result
print("The extracted dictionary: " + str(res))


Output

The original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}

Time Complexity: The time complexity of this approach depends on the size of the dictionary and the length of the req_list.
Auxiliary Space: The space complexity of this approach is O(n), where n is the number of items in the dictionary. 

Method 6 : using list comprehension

Step-by-step approach:

  • Define the original dictionary test_dict with keys and values.
  • Print the original dictionary using print().
  • Define req_list as the required list of values.
  • Create an empty dictionary result_dict.
  • Use a for loop to iterate through the items in test_dict using .items().
  • Check if all the values of the current item are in req_list using all().
  • If all values are in req_list, add the key-value pair to result_dict.
  • Print the extracted dictionary using print().

Python3




test_dict = {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
print("The original dictionary: " + str(test_dict))
 
req_list = [4, 6, 10]
 
result_dict = {}
 
for key, values in test_dict.items():
    if all(val in req_list for val in values):
        result_dict[key] = values
 
print("The extracted dictionary: " + str(result_dict))


Output

The original dictionary: {'gfg': [4, 6], 'is': [10], 'best': [4, 5, 7]}
The extracted dictionary: {'gfg': [4, 6], 'is': [10]}

The time complexity of this code is O(N*M), where N is the number of keys in the dictionary and M is the maximum length of the lists in the dictionary. 
The auxiliary space complexity of this code is O(N), where N is the number of keys in the dictionary. 



Last Updated : 10 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads