In this article let’s learn how to convert a list of dictionaries into a list of lists. We often fall in need of this type of conversion, especially when we develop web applications. Let’s take an example to understand this scenario.
We have a list of dictionaries named list_of_dict with the following keys and values.
Example:
list-of-dict = [['One': 1, 'Two': 2, 'Three': 3}, {'One': 2, 'Two': 3, 'Three': 4}]
Output:
We can now convert this list of dictionaries into a list of lists using the following two ways:
- Using loop with enumerate()
- Using list comprehension.
Using loop with enumerate():
Python has been enabled with an inbuilt function enumerate(), which enables us to keep count of the number of iterations done in a loop. This method adds a counter named start which gets initialised as 0, to an iterable.
enumerate(iterable, start=0)
Example:
list-of-dict = [['One': 1, 'Two': 2, 'Three': 3}, {'One': 2, 'Two': 3, 'Three': 4}] print("Given list of dictionaries : " + str(list_of_dict)) list_of_list = [] for i, ele in enumerate(list_of_dict, start = 0): if i == 0: list_of_list.append(list(ele.keys())) list_of_list.append(list(ele.values())) else: list_of_list.append(list(ele.values())) # printing result print("The converted list : " + str(list_of_list))
Output:
In the above code, we create an empty list named list_of_list in which we store the converted list. The iterable used in the enumerate() function is list_of_dict and the iterators used in the for loop are i and ele. ‘i’ to iterate the new list and ‘ele’ to iterate through the list_of_dict.
Using list comprehension:
Before knowing how to solve using this method. Please refer to this article about list comprehension
https://www.i2tutorials.com/list-comprehensions/
Example:
list-of-dict = [['One': 1, 'Two': 2, 'Three': 3}, {'One': 2, 'Two': 3, 'Three': 4}] print("Given list of dictionaries : " + str(list_of_dict)) list_of_list = [[key for key in list_of_dict[0].keys()], *list(i.values()) for i in list_of_dict]] print("The converted list : " + str(list_of-list))
Output:
We have taken the same list_of _dict example and we are using list comprehension to write a one-line code for the conversion.