![]() |
VOOZH | about |
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list.
Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7}
Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks']
Explanation : "Gfg" is replaced, followed by its value in dictionary.Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"gfg" : 7, "best" : 8}
Output : ['Gfg', 'is', 'Best', 'For', 'Geeks']
Explanation : No replacement. No matching values.
Method #1 : Using list comprehension + get()
The combination of above functionalities can be used to solve this problem. In this, we append all the key if present checking using get(), along with values in list.
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks'] The list after substitution : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks', 8]
Time Complexity: O(n), where n is the elements of dictionary
Auxiliary Space: O(n), where n is the size of dictionary
Method #2 : Using chain.from_iterable() + list comprehension
This is yet another way in which this task can be performed. In this, we form key value pair list and append if present and if not retain the element. Next, the flattening of key-value lists is performed using chain.from_iterable().
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks'] The list after substitution : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks', 8]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #3: Using a for loop and append method for flattening the dictionary:
Step-by-step approach:
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks'] The list after substitution : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks', 8]
Time complexity: O(n) where n is the length of the input list.
Auxiliary space: O(n) where n is the length of the input list.