Open In App

Python – Convert List of Dictionaries to List of Lists

Last Updated : 28 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 discuss certain ways in which this task can be performed.

Input: test_list = [{'Gfg': 123, 'best': 10}, {'Gfg': 51, 'best': 7}] 
Output : [['Gfg', 'best'], [123, 10], [51, 7]] 

Input : test_list = [{'Gfg' : 12}] 
Output : [['Gfg'], [12]]

Explanation: In This, we are converting list of dictionaries to list of lists in Python.

Convert List of Dictionaries to List of Lists using Loop

A combination of above methods can be used to perform this task. In this, we perform the task of iterating using loop and brute force with the help of enumerate() to perform appropriate append in the result list. 

Python3




# Using loop + enumerate()
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
             {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
             {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
res = []
for idx, sub in enumerate(test_list, start = 0):
    if idx == 0:
        res.append(list(sub.keys()))
        res.append(list(sub.values()))
    else:
        res.append(list(sub.values()))
 
print("The converted list : " + str(res))


Output

The original list is : [{'Akash': 18, 'Nikhil': 17, 'Akshat': 20}, {'Akash': 30, 'Nikhil': 21, 'Akshat': 10}, {'Akash': 12, 'Nikhil': 31, 'Akshat': 19}]
The converted list : [['Akash', 'Nikhil', 'Akshat'], [18, 17, 20], [30, 21, 10], [12, 31, 19]]

Time complexity: O(n * m), where n is the number of dictionaries in the list test_list and m is the number of keys in each dictionary. 
Auxiliary space: O(n * m), where n is the number of dictionaries in the list test_list and m is the number of keys in each dictionary. 

Convert List of Dictionaries to List of Lists using List Comprehension 

This task can be solved in one line using list comprehension. In this, we extract the keys initially using keys() and values using values(). 

Python3




# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using list comprehension
 
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
             {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
             {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert List of Dictionaries to List of Lists
# Using list comprehension
res = [[key for key in test_list[0].keys()], *[list(idx.values()) for idx in test_list ]]
 
# printing result
print("The converted list : " + str(res))


Output

The original list is : [{'Akash': 18, 'Nikhil': 17, 'Akshat': 20}, {'Akash': 30, 'Nikhil': 21, 'Akshat': 10}, {'Akash': 12, 'Nikhil': 31, 'Akshat': 19}]
The converted list : [['Akash', 'Nikhil', 'Akshat'], [18, 17, 20], [30, 21, 10], [12, 31, 19]]

Time complexity: O(n * m), where n is the number of dictionaries in the list and m is the average number of keys in each dictionary.
Auxiliary space: O(n * m), as we are creating a new list of lists to store the converted result.

Convert List of Dictionaries to List of Lists using Map() function and Lambda function

In this approach, the lambda function takes a dictionary as an argument, extracts its values, and returns them as a list. The map() function applies this lambda function to each dictionary in the list and returns a list of lists. The first list in the result is the keys from the first dictionary in the original list. Finally, we use the insert() method to add this list as the first element in the result list.

Python3




# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using map() function and lambda function
 
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
             {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
             {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert List of Dictionaries to List of Lists
# Using map() function and lambda function
res = list(map(lambda x: list(x.values()), test_list))
res.insert(0, list(test_list[0].keys()))
 
# printing result
print("The converted list : " + str(res))


OUTPUT:

The original list is : [{'Nikhil': 17, 'Akash': 18, 'Akshat': 20}, {'Nikhil': 21, 'Akash': 30, 'Akshat': 10}, {'Nikhil': 31, 'Akash': 12, 'Akshat': 19}]
The converted list : [['Nikhil', 'Akash', 'Akshat'], [17, 18, 20], [21, 30, 10], [31, 12, 19]]

Time complexity: O(nm), where n is the number of dictionaries in the list and m is the number of key-value pairs in each dictionary.
Auxiliary space: O(nm), where n is the number of dictionaries in the list and m is the number of key-value pairs in each dictionary.

Convert List of Dictionaries to List of Lists using Pandas Library

  1. Import the pandas library.
  2. Convert the list of dictionaries to a pandas dataframe using the “pd.DataFrame()” method.
  3. Use the “values.tolist()” method to convert the dataframe to a list of lists.
  4. Extract the column names from the dataframe and insert them as the first element of the resulting list of lists.

Python3




# Importing the pandas library
import pandas as pd
 
# Initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
             {'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
             {'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
 
# Converting List of Dictionaries to List of Lists using pandas
df = pd.DataFrame(test_list)
res = df.values.tolist()
res.insert(0, list(df.columns))
 
# Printing the result
print("The converted list : " + str(res))


OUTPUT;

The converted list : [['Nikhil', 'Akash', 'Akshat'], [17, 18, 20], [21, 30, 10], [31, 12, 19]]

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

Convert List of Dictionaries to List of Lists using Zip() function

Use the built-in zip() function and list() method to convert the list of dictionaries to a list of lists.

Step-by-step approach:

  • Initialize an empty list to hold the final result.
  • Extract the keys from the first dictionary in the input list and append them as a list to the final result list.
  • Extract the values from each dictionary in the input list and append them as a list to the final result list using the zip() function.
  • Return the final result list.

Below is the implementation of the above approach:

Python3




test_list = [{'Nikhil': 17, 'Akash': 18, 'Akshat': 20},
             {'Nikhil': 21, 'Akash': 30, 'Akshat': 10},
             {'Nikhil': 31, 'Akash': 12, 'Akshat': 19}]
 
# printing original list
print("The original list is: " + str(test_list))# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using zip() and list()
 
# Convert List of Dictionaries to List of Lists
# Using zip() and list()
keys = list(test_list[0].keys())
values = [list(x.values()) for x in test_list]
res = [keys] + list(zip(*values))
 
# printing result
print("The converted list : " + str(res))
 
 
# Convert List of Dictionaries to List of Lists
# Using zip() function and list() constructor
res = []
keys = list(test_list[0].keys())
res.append(keys)
for d in test_list:
    values = [d[key] for key in keys]
    res.append(values)
 
# printing result
print("The converted list is: " + str(res))


Output

The original list is: [{'Nikhil': 17, 'Akash': 18, 'Akshat': 20}, {'Nikhil': 21, 'Akash': 30, 'Akshat': 10}, {'Nikhil': 31, 'Akash': 12, 'Akshat': 19}]
The original list is : [{'Nikhil': 17, 'Akash': 18, 'Akshat': 20}, {'Nikhil': 21, 'Akash': 30, 'Akshat': 10}, {'Nikhil': 31, 'Akash': 12, 'Akshat': 19}]
The converted list : [['Nikhil', 'Akash', 'Akshat'], (17, 21, 31), (18, 30, 12), (20, 10, 19)]
The converted list is: [['Nikhil', 'Akash', 'Akshat'], [17, 18, 20], [21, 30, 10], [31, 12, 19]]

Time complexity: O(n^2), where n is the number of dictionaries in the input list.
Auxiliary space: O(n), where n is the number of dictionaries in the input list.



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 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
Python | Split dictionary of lists to list of dictionaries
Conversion from one data type to other is essential in various facets of programming. Be it development or competitive programming. Hence knowledge of it is quite useful and necessary. Let's discuss certain methods by which dictionary of list can be converted to the corresponding list of dictionaries. Method #1 : Using list comprehension We can use
4 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 List to List of dictionaries
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_li
5 min read
Python - Values frequency across Dictionaries lists
Given two list of dictionaries, compute frequency corresponding to each value in dictionary 1 to second. Input : test_list1 = [{"Gfg" : 6}, {"best" : 10}], test_list2 = [{"a" : 6}, {"b" : 10}, {"d" : 6}}] Output : {'Gfg': 2, 'best': 1} Explanation : 6 has 2 occurrence in 2nd list, 10 has 1. Input : test_list1 = [{"Gfg" : 6}], test_list2 = [{"a" : 6
6 min read
Python - Dictionaries with Unique Value Lists
Given List of dictionaries with list values, extract unique dictionaries. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] Output : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] Explanation : Both are similar dictionaries, and hence 1 is removed. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' :
4 min read
three90RightbarBannerImg