Open In App

Python – Assigning Key values to list elements from Value list Dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Given a List of elements, map them with keys of matching values from a value list.

Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} 
Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] 
Explanation : 4 is present in "is" key, hence mapped in new list. 
Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [18, 14]} 
Output : ['Gfg', 'Gfg', 'Gfg', 'Gfg'] 
Explanation : All elements present in "Gfg" key.

Method #1: Using list comprehension

This is one of the ways in which this task can be performed. In this, we extract each element of dictionary value list to checklist value occurrence, if matched, we assign that key’s value to that index.

Python3




# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using list comprehension
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
 
# nested loop inside list comprehension to check each key
res = [key for ele in test_list
       for key, val in test_dict.items() if ele in val]
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']

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

Method #2 : Using dictionary comprehension + list comprehension

This is yet another way in which this task can be performed.  In this we create inverse dictionary, and map each list value with its key, post that each key is mapped with argument key list elements for matching key value.

Python3




# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using dictionary comprehension + list comprehension
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
 
# creating inverse dictionary of elements
temp = {j : i for i, k in test_dict.items() for j in k}
 
# creating end result by mapping elements
res = [temp.get(key) for key in test_list]
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']

Time Complexity: O(n*n) where n is the number of elements in the dictionary.
Auxiliary Space: O(n), where n is the number of elements in the dictionary.

Method 3: Using nested for loops

  • Initialize the input list test_list.
  • Print the original list.
  • Initialize the dictionary test_dict where the keys are strings and the values are lists of integers.
  • Create an empty list res to store the filtered values.
  • Iterate through each element ele in test_list.
  • For each element, iterate through each key-value pair in test_dict.
  • Check if the current element ele is present in the value list of the current key-value pair.
  • If the element is present, append the corresponding key to the result list res.
  • Print the filtered list res.

Python3




# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using nested for loop
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
 
# creating an empty list to store the filtered values
res = []
 
# iterating through the test_list and test_dict
for ele in test_list:
    for key, val in test_dict.items():
        if ele in val:
            res.append(key)
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']

Time complexity: O(N*M), where n is the length of test_list and m is the average length of the lists in test_dict.
Auxiliary space: O(N)

Method #4: Using a generator function

Step-by-step approach:

  • Loop through each key-value pair in the test_dict dictionary, and check if the current element ele is present in the list of values associated with that key.
  • If the current element is present in the list of values, yield the corresponding key.
    • Call the generator function using a generator expression within the list() function, and store the result in the res list.
  • Finally, print the result using the print() function

Step-by-step approach:

Python3




# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using generator function
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
 
# generator function to get keys for given element
def get_keys(ele, d):
    for key, val in d.items():
        if ele in val:
            yield key
 
# creating an empty list to store the filtered values
res = []
 
# iterating through the test_list and calling the generator function for each element
for ele in test_list:
    keys = list(get_keys(ele, test_dict))
    if len(keys) > 0:
        res.append(keys[0])
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']

Time complexity: O(n*m), where n is the length of test_list, and m is the number of key-value pairs in test_dict.
Auxiliary Space: O(1), as we are using a generator function which only stores the current element and dictionary key-value pairs in memory. 

Method #5: Using map() function and lambda expression

Step-by-step approach:

  • Convert the dictionary values into a set for faster lookup.
  • Use the map() function and a lambda expression to iterate over each element in the original list and return the corresponding keys.
  • Convert the result to a list.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg": [5, 3, 6], "is": [8, 4], "Best": [10, 11]}
 
# converting dictionary values to set
val_set = set(val for lst in test_dict.values() for val in lst)
 
# using map() function and lambda expression to get corresponding keys
res = list(map(lambda x: [k for k, v in test_dict.items() if x in v][0], filter(lambda x: x in val_set, test_list)))
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']

Time complexity: O(n*m), where n is the length of the original list and m is the length of the longest value list in the dictionary.
Auxiliary space: O(k), where k is the number of elements in the filtered list.

Method #6: Using defaultdict from collections module

Python3




from collections import defaultdict
 
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
 
# using defaultdict to store keys with multiple values
temp_dict = defaultdict(list)
for key, val in test_dict.items():
    for v in val:
        temp_dict[v].append(key)
 
# creating result list using list comprehension and temp_dict
res = [temp_dict[ele] for ele in test_list if ele in temp_dict]
 
# printing result
print("The filtered list : " + str(res))


Output

The original list : [4, 6, 3, 10, 5, 3]
The filtered list : [['is'], ['Gfg'], ['Gfg'], ['Best'], ['Gfg'], ['Gfg']]

Time Complexity: O(n * m), where n is the length of the test_list and m is the total number of values in the test_dict.
Auxiliary Space: O(m), where m is the total number of values in the test_dict.



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