Open In App

Python – Convert Dictionaries List to Order Key Nested dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value.

Input : test_list = [{“Gfg” : 3, 4 : 9}, {“is”: 8, “Good” : 2}] 
Output : {0: {‘Gfg’: 3, 4: 9}, 1: {‘is’: 8, ‘Good’: 2}} 
Explanation : List converted to dictionary with index keys. 

Input : test_list = [{“is”: 8, “Good” : 2}] 
Output : {1: {‘is’: 8, ‘Good’: 2}} 
Explanation : List converted to dictionary with index keys, just one row.

Method #1 : Using loop + enumerate()

This is brute way in which this task can be performed. In this, we iterate through the index and value together using enumerate and create custom required dictionary.

Step-by-step approach:

  • The program initializes a list test_list containing three dictionaries with different key-value pairs.
  • The original list is printed using the print() function.
  • The program creates an empty dictionary res.
  • Using a for loop and the enumerate() function, the program iterates over each dictionary in the test_list. The enumerate() function returns a tuple containing the index and the dictionary itself, which are assigned to idx and val, respectively.
  • Inside the loop, the program creates a new key-value pair in the res dictionary where the key is the index of the current dictionary, and the value is the dictionary itself.
  • After the loop completes, the resulting nested dictionary is printed using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert Dictionaries List to Order Key Nested dictionaries
# Using loop + enumerate()
 
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# using enumerate() to extract key to map with dict values
res = dict()
for idx, val in enumerate(test_list):
    res[idx] = val
     
# printing result
print("The constructed dictionary : " + str(res))


Output

The original list : [{'Gfg': 3, 4: 9}, {'is': 8, 'Good': 2}, {'Best': 10, 'CS': 1}]
The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

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

Method #2 : Using dictionary comprehension + enumerate() 

This is similar to above method, the only difference is that dictionary comprehension is used instead of loop to perform task of encapsulation.

Python3




# Python3 code to demonstrate working of
# Convert Dictionaries List to Order Key Nested dictionaries
# Using dictionary comprehension + enumerate()
 
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# dictionary comprehension encapsulating result as one liner
res = {idx : val for idx, val in enumerate(test_list)}
     
# printing result
print("The constructed dictionary : " + str(res))


Output

The original list : [{'Gfg': 3, 4: 9}, {'is': 8, 'Good': 2}, {'Best': 10, 'CS': 1}]
The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

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

Method #3: Using a list comprehension

One simple way to create a dictionary from a list of items is to use a list comprehension. We can iterate over the list and use enumerate() to generate the keys for the dictionary. 

Python3




# Initializing the list
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
 
# Using a dictionary comprehension with enumerate() to create a dictionary
# The enumerate() function returns tuples of the form (index, value) for each element in the list
# We use these tuples to map the index to the corresponding dictionary in the list
res = {i: val for i, val in enumerate(test_list)}
 
# Printing the resulting dictionary
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

Time Complexity: O(n), where n is the length of test_list.
Auxiliary Space: O(n)

 Method 4: Built-in function map() along with the enumerate() function.

This method maps each element of the given iterable (in this case, the list test_list) to the corresponding tuple of the form (index, value) using enumerate(), and then creates a dictionary using these tuples as key-value pairs.

Python3




test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
 
# Using map() with enumerate() to create a dictionary
res = dict(map(lambda x: (x[0], x[1]), enumerate(test_list)))
 
# Printing the resulting dictionary
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

Time complexity: O(n), where n is the length of the input list test_list,
Auxiliary Space: O(n), where n is the length of the input list test_list. 

Method #5: Using the built-in function zip() and a list comprehension

This method creates a range of indices using the range() function, which is then combined with the original list using the zip() function. The resulting pairs of index and dictionary are then used to construct the final dictionary using a dictionary comprehension.

Python3




test_list = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}, {"Best": 10, "CS": 1}]
 
# using zip() to combine the list with a range of indices
res = {i: d for i, d in zip(range(len(test_list)), test_list)}
 
# printing result
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), because a new dictionary is created that has the same number of elements as the original list.

Method 6: Using a lambda function with map() and enumerate()

In this method, we use the lambda function to extract the key-value pairs from the enumerated test_list, and then we use the map function to create a list of tuples from these pairs. Finally, we pass this list of tuples to the dict() constructor to create the nested dictionary.

Python3




# Python3 code to demonstrate working of
# Convert Dictionaries List to Order Key Nested dictionaries
# Using lambda function with map() and enumerate()
 
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# using lambda function with map() and enumerate() to create a nested dictionary
res = dict(map(lambda x: (x[0], x[1]), enumerate(test_list)))
 
# printing result
print("The constructed dictionary : " + str(res))


OUTPUT:The original list :
 [{'Gfg': 3, 4: 9}, {'is': 8, 'Good': 2}, {'Best': 10, 'CS': 1}]
The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

Time complexity: O(n), where n is the number of dictionaries in the test_list. 
Auxiliary space: O(n), where n is the number of dictionaries in the test_list. 



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