/  Technology   /  Convert list of lists to list of dictionaries

Convert list of lists to list of dictionaries

In the previous article, we have discussed how to convert a list of dictionaries into a list of lists. In this article let’s discuss how to do the converse of this i.e. learn how to convert a list of lists into a list of dictionaries when a separate list that has the data of keys is given to us.

Let us first understand this scenario with an example. We have a list named list_of_list with the following elements.

We have another list named dict_keys which has the keys for the list of dictionaries that we are creating.

We now have to get the output in this form which is a list of dictionaries.

We can achieve this using two methods:

  • Using list comprehension
  • Using dictionary comprehension

 

Before we learn these methods, having prior knowledge about list comprehension and dictionary comprehension is appreciated. So please refer to the articles below

https://www.i2tutorials.com/list-comprehensions/

https://docs.google.com/document/d/13bMIsQim-pDQTk2crKPrbxSGlvGKqt_8ZU_UMGo8MqI/edit?usp=sharing

 

Using list comprehension:

We are using the dict() function along with the zip() function which will zip the values of elements in the list dict_keys and the lists in the list_of_list and store them in a list named list_of_dict.

[ dict (zip(dict_keys, i)) for i in list_of_list ]

 

Using dictionary comprehension:

The implementation is much similar to that of list comprehension. We use a zip() function here which again does the same task as above in the one-liner code using dictionary comprehension and stores it in a list named list_of_dict.

 

list_of_dict = [{ k:v for k,v in zip(dict_keys, i) } for i in list_of_list]

Leave a comment