Open In App

Python – Convert Dictionaries List to Order Key Nested dictionaries

Last Updated : 21 Mar, 2023
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. 



Similar Reads

Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python - Convert Flat dictionaries to Nested dictionary
Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can convert flat dictionaries into nested dictionaries. Conv
4 min read
Python - Convert String to Nested Dictionaries
Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let's discuss certain way in which this task can be done. Method : Using loop + recursion Th
2 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Filter List of Python Dictionaries by Key in Python
Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
3 min read
Python - Convert Nested Tuple to Custom Key Dictionary
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this t
4 min read
Python - Convert List of Dictionaries to List of Lists
Sometimes, while working with Python data, we can have a problem in which we need to convert the list of dictionaries into a list of lists, this can be simplified by appending the keys just once if they are repetitive as mostly in records, this saves memory space. This type of problem can have applications in the web development domain. Let's discu
7 min read