VOOZH about

URL: https://www.geeksforgeeks.org/python/python-flatten-dictionary-with-list/

⇱ Python - Flatten Dictionary with List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Flatten Dictionary with List

Last Updated : 21 Apr, 2023

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.


Output
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().


Output
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:

  • Create an empty list called res.
  • Iterate through each element ele in test_list.
  • If ele is a key in subs_dict, then append ele and the corresponding value from subs_dict to res.
  • Otherwise, append ele to res.
  • Print the resulting list res.

Output
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.

Comment