/  Technology   /  Splitting a dictionary of lists into a list of dictionaries

Splitting a dictionary of lists into a list of dictionaries

We, as developers, often fall in need for the conversion from one data type to another. One such type conversion is conversion of a dictionary of lists to a list of dictionaries.

Let’s understand this first by taking an example. Below is a dictionary with the following keys and its corresponding values are lists.

Now, we have to convert this into something like the below mentioned list where its elements are dictionaries.

We have two ways of achieving this:

  1. Using list comprehension
  2. Using zip()

 

Using list comprehension:

List Comprehension is a way of writing a more concise code for various scenarios and also increasing the code’s readability.

To learn more about list comprehension, please refer this article

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

 

Now we have our dictionary of lists stored in a variable named ‘x’. We iterate through the elements of the dictionary using a for loop, build the corresponding list of dictionaries simultaneously with the help of a one liner code(list comprehension) and store it in a variable named result.

 

result = [{key : value[i] for key, value in x.items()}

 for i in range(2)]

 

Using the zip() function:

The zip() function combines two or more iterables like lists, strings, dictionaries, etc. It maps the similar index of multiple containers.

We have taken the same example x which is a dictionary of lists. In this method, we have used the zip() function twice, once when we zip all the particular index values of all the lists as one and then again to zip it with the corresponding keys once we get all the values of a particular index and store the final List of Dictionaries in a variable named result.

 

Leave a comment