/  Technology   /  How to convert a list of dictionaries into a list of lists?

How to convert a list of dictionaries into a list of lists?

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.

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)

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/

We have taken the same list_of _dict example and we are using list comprehension to write a one-line code for the conversion. 

 

Leave a comment