Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Convert List of Dictionaries to List of Lists

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 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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments