Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert list to nestings, i.e each list values representing new nested level. This kind of problem can have application in many domains including web development. Lets discuss the certain way in which this task can be performed.
Method 1: Using zip() + list comprehension
The combination of above functions can be combined to perform this task. In this, we iterate for zipped list and render the nested dictionaries using list comprehension.
Python3
# Python3 code to demonstrate working of # Convert Lists to Nestings Dictionary # Using list comprehension + zip() # initializing list test_list1 = ["gfg", 'is' , 'best' ] test_list2 = [ 'ratings' , 'price' , 'score' ] test_list3 = [ 5 , 6 , 7 ] # printing original list print ("The original list 1 is : " + str (test_list1)) print ("The original list 2 is : " + str (test_list2)) print ("The original list 3 is : " + str (test_list3)) # Convert Lists to Nestings Dictionary # Using list comprehension + zip() res = [{a: {b: c}} for (a, b, c) in zip (test_list1, test_list2, test_list3)] # printing result print ("The constructed dictionary : " + str (res)) |
The original list 1 is : ['gfg', 'is', 'best'] The original list 2 is : ['ratings', 'price', 'score'] The original list 3 is : [5, 6, 7] The constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]
Time complexity: O(n) because it uses list comprehension to create a new list with the same number of elements as the input lists, and then the zip() function iterates over all the elements of the input lists once. Therefore, the time complexity is linear with respect to the length of the input lists.
Auxiliary space: O(n) because it creates a new list with the same number of elements as the input lists, which requires O(n) space. Additionally, it creates a dictionary for each element of the new list, which requires O(1) space, so the overall auxiliary space complexity is also O(n).
Method 2: Naive (Using for loop)
Convert the given lists into a nested dictionary is by using a for loop to iterate through each element of the lists and adding the elements into the dictionary.
- Initialize three lists with the given data.
- Initialize an empty dictionary to store the nested dictionary.
- Iterate through the length of the first list using a for loop.
- Inside the for loop, create a sub-dictionary with the elements of the second and third lists at the current index.
- Add the sub-dictionary to the result dictionary using the element of the first list at the current index as the key.
- After the for loop completes, print the constructed dictionary.
Example:
Python3
# initializing lists test_list1 = [ "gfg" , 'is' , 'best' ] test_list2 = [ 'ratings' , 'price' , 'score' ] test_list3 = [ 5 , 6 , 7 ] # initializing dictionary result_dict = {} # iterating through the lists for i in range ( len (test_list1)): sub_dict = {test_list2[i]: test_list3[i]} result_dict[test_list1[i]] = sub_dict # printing result print ( "The constructed dictionary : " + str (result_dict)) |
The constructed dictionary : {'gfg': {'ratings': 5}, 'is': {'price': 6}, 'best': {'score': 7}}
Time Complexity: O(n), where n is the length of the lists
Auxiliary Space: O(n), where n is the length of the lists
Method 3 : Using dictionary comprehension
- We start by initializing three lists, test_list1, test_list2, and test_list3, each containing some values.
- We use the zip function to create a new list of tuples, where each tuple contains the corresponding elements from test_list1, test_list2, and test_list3. For example, the first tuple will contain the first elements from all three lists, the second tuple will contain the second elements from all three lists, and so on. We pass the three lists as arguments to the zip function.
- We use dictionary comprehension to create a nested dictionary. The outer dictionary will have keys from test_list1, and the values will be inner dictionaries. The inner dictionaries will have keys from test_list2 and values from test_list3.
- We iterate over each tuple in the list created by zip, and unpack the elements of the tuple into three variables a, b, and c. We use these variables to create a new dictionary with b as the key and c as the value.
- We use the variable a as the key for the outer dictionary, and assign the dictionary created in step 4 as the value for this key.
- We assign the resulting nested dictionary to the variable res.
- We print the resulting nested dictionary by using the print function, along with a string that describes the dictionary.
Python3
# initializing lists test_list1 = [ "gfg" , 'is' , 'best' ] test_list2 = [ 'ratings' , 'price' , 'score' ] test_list3 = [ 5 , 6 , 7 ] # using dictionary comprehension to create a nested dictionary res = {a: {b: c} for (a, b, c) in zip (test_list1, test_list2, test_list3)} # printing the resulting dictionary print ( "The constructed dictionary: " , res) |
The constructed dictionary: {'gfg': {'ratings': 5}, 'is': {'price': 6}, 'best': {'score': 7}}
The time complexity of this method is O(n), where n is the length of the input lists, since we are iterating over each element in the zipped list.
The auxiliary space is also O(n), since we are creating a dictionary to store the nested dictionary.
Method 4 : using the itertools module:
- Import the itertools module.
- Initialize the three lists: test_list1, test_list2, and test_list3.
- Create an iterator cycle_lists using itertools.cycle() that cycles through the three lists.
- Initialize an empty dictionary res to store the result.
- Start a loop to iterate over the combined elements of the lists using zip() and next() functions:
- In each iteration of the loop, the zip() function combines the next element from each list into a tuple (a, b, c).
The next(cycle_lists) is used to fetch the next list in a cyclic manner.
Assign the values from the tuple to variables a, b, and c.
Create a nested dictionary {b: c}.
Assign the nested dictionary to the key a in the outer dictionary res. - Print the resulting dictionary res.
Python3
import itertools # Initializing lists test_list1 = [ "gfg" , 'is' , 'best' ] test_list2 = [ 'ratings' , 'price' , 'score' ] test_list3 = [ 5 , 6 , 7 ] # Creating an iterator that cycles through the lists cycle_lists = itertools.cycle([test_list1, test_list2, test_list3]) # Initializing an empty dictionary res = {} # Iterating over the combined elements of the lists for a, b, c in zip ( next (cycle_lists), next (cycle_lists), next (cycle_lists)): res[a] = {b: c} # Printing the resulting dictionary print ( "The constructed dictionary: " , res) |
The constructed dictionary: {'gfg': {'ratings': 5}, 'is': {'price': 6}, 'best': {'score': 7}}
Time complexity of this code is O(n).
Auxiliary space: O(1) as no additional data structures are used except the input lists and the resulting dictionary.