![]() |
VOOZH | about |
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.
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.
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
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:
Step-by-step approach:
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:
Below is the implementation of the above approach:
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
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.