Open In App

Python – Convert List to List of dictionaries

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given list values and keys list, convert these values to key value pairs in form of list of dictionaries.

Input : test_list = [“Gfg”, 3, “is”, 8], key_list = [“name”, “id”] 
Output : [{‘name’: ‘Gfg’, ‘id’: 3}, {‘name’: ‘is’, ‘id’: 8}] 
Explanation : Values mapped by custom key, “name” -> “Gfg”, “id” -> 3. 

Input : test_list = [“Gfg”, 10], key_list = [“name”, “id”] 
Output : [{‘name’: ‘Gfg’, ‘id’: 10}] 
Explanation : Conversion of lists to list of records by keys mapping.

Method #1 : Using loop + dictionary comprehension

This is one of the ways in which this task can be performed. In this, we perform mapping values using dictionary comprehension. The iteration is performed using loop.

Python3




# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using dictionary comprehension + loop
 
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing key list
key_list = ["name", "number"]
 
# loop to iterate through elements
# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
    res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
 
# printing result
print("The constructed dictionary list : " + str(res))


Output

The original list : [‘Gfg’, 3, ‘is’, 8, ‘Best’, 10, ‘for’, 18, ‘Geeks’, 33] The constructed dictionary list : [{‘name’: ‘Gfg’, ‘number’: 3}, {‘name’: ‘is’, ‘number’: 8}, {‘name’: ‘Best’, ‘number’: 10}, {‘name’: ‘for’, ‘number’: 18}, {‘name’: ‘Geeks’, ‘number’: 33}]

Time Complexity: O(n*n) where n is the number of elements in the dictionary
Auxiliary Space: O(n), where n is the number of elements in the dictionary

Method #2 : Using dictionary comprehension + list comprehension

The combination of above functions is used to solve this problem. In this, we perform a similar task as above method. But difference is that its performed as shorthand.

Python3




# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using zip() + list comprehension
 
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing key list
key_list = ["name", "number"]
 
# using list comprehension to perform as shorthand
n = len(test_list)
res = [{key_list[0]: test_list[idx], key_list[1]: test_list[idx + 1]}
       for idx in range(0, n, 2)]
 
# printing result
print("The constructed dictionary list : " + str(res))


Output

The original list : [‘Gfg’, 3, ‘is’, 8, ‘Best’, 10, ‘for’, 18, ‘Geeks’, 33] The constructed dictionary list : [{‘name’: ‘Gfg’, ‘number’: 3}, {‘name’: ‘is’, ‘number’: 8}, {‘name’: ‘Best’, ‘number’: 10}, {‘name’: ‘for’, ‘number’: 18}, {‘name’: ‘Geeks’, ‘number’: 33}]

Method #3: Using zip function and dictionary comprehension

The zip() function creates pairs of corresponding elements from the two lists, and the enumerate() function is used to iterate over the key_list to assign the keys to the dictionary. Finally, the dictionary comprehension is used to construct the dictionaries.

Python3




# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
 
# initializing key list
key_list = ["name", "number"]
 
# using zip() function and dictionary comprehension
res = [{key_list[i]: val for i, val in enumerate(pair)} for pair in zip(test_list[::2], test_list[1::2])]
 
# printing result
print("The constructed dictionary list : " + str(res))


Output

The constructed dictionary list : [{'name': 'Gfg', 'number': 3}, {'name': 'is', 'number': 8}, {'name': 'Best', 'number': 10}, {'name': 'for', 'number': 18}, {'name': 'Geeks', 'number': 33}]

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 4: Use the groupby() function from the itertools module. 

Step-by-step approach:

  • Import the itertools module.
  • Initialize an empty list res.
  • Use the groupby() function to group the test_list into pairs based on the remainder when the index is divided by 2.
  • For each pair of elements, create a dictionary with keys “name” and “number“.
  • Append each dictionary to the res list.
  • Convert the res list to a string and print the result.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using groupby() function from itertools module
 
# import itertools module
import itertools
 
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing key list
key_list = ["name", "number"]
 
# using groupby() function to group elements into pairs
res = []
for pair in zip(test_list[::2], test_list[1::2]):
    res.append({key_list[0]: pair[0], key_list[1]: pair[1]})
 
# printing result
print("The constructed dictionary list : " + str(res))


Output

The original list : ['Gfg', 3, 'is', 8, 'Best', 10, 'for', 18, 'Geeks', 33]
The constructed dictionary list : [{'name': 'Gfg', 'number': 3}, {'name': 'is', 'number': 8}, {'name': 'Best', 'number': 10}, {'name': 'for', 'number': 18}, {'name': 'Geeks', 'number': 33}]

Time complexity: O(N), where N is the length of the input list.
Auxiliary space: O(N), since we create a new list of tuples using the zip() function.



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
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 :
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 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
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
Python - Convert list of dictionaries to Dictionary Value list
Given a list of dictionary, convert to dictionary with same key mapped with all values in as value list. Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}] Output : {'Gfg': [6, 8], 'is': [9, 11], 'best': [10, 19]} Explanation : 6, 8 of "Gfg" mapped as value list, similarly every other. Input : test_list =
10 min read
Python - Convert String to List of dictionaries
Given List of dictionaries in String format, Convert into actual List of Dictionaries. Input : test_str = ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 8}]"] Output : [[{'Gfg': 3, 'Best': 8}, {'Gfg': 4, 'Best': 8}]] Explanation : String converted to list of dictionaries. Input : test_str = ["[{'Gfg' : 3, 'Best' : 8}]"] Output : [[{'Gfg': 3, 'Bes
4 min read
Python program to Convert Matrix to List of dictionaries
Given a Matrix, convert it to a list of dictionaries by mapping similar index values. Input : test_list = [["Gfg", [1, 2, 3]], ["best", [9, 10, 11]]] Output : [{'Gfg': 1, 'best': 9}, {'Gfg': 2, 'best': 10}, {'Gfg': 3, 'best': 11}] Input : test_list = [["Gfg", [1, 2, 3]]] Output : [{'Gfg': 1}, {'Gfg': 2}, {'Gfg': 3}] Method #1: The brute way in whic
4 min read
Python Program to Convert dictionary string values to List of dictionaries
Given a dictionary with values as delimiter separated values, the task is to write a python program to convert each string as different value in list of dictionaries. Input : test_dict = {"Gfg" : "1:2:3", "best" : "4:8:11"} Output : [{'Gfg': '1', 'best': '4'}, {'Gfg': '2', 'best': '8'}, {'Gfg': '3', 'best': '11'}] Explanation : List after dictionar
2 min read
Python - Convert list of dictionaries to dictionary of lists
In this article, we will discuss how to convert a list of dictionaries to a dictionary of lists. Method 1: Using for loop By iterating based on the first key we can convert list of dict to dict of list. Python program to create student list of dictionaries C/C++ Code # create a list of dictionaries # with student data data = [ {'name': 'sravan', 's
3 min read
three90RightbarBannerImg