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

Splitting a dictionary of lists into a list of dictionaries in Python

 

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.

 

Example:

{'One':[1, 2], 'Two': [2, 3], 'Three': [3, 4]}

 

Output:

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

 

Example:

[{'One':1, 'Two': 2, 'Three': 3}, {'One': 2, 'Two': 3, 'Three': 4}]

 

Output:

 

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

list comprehension

 

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)]

 

Example:

x = {'One':[1, 2], 'Two': [2, 3], 'Three': [3, 4]}

print ("Dictionary of lists : " + str(x))

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

print ("Final List of dictionaries: " + str(result))

 

Output:

 

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.

 

Example:

x = {'One':[1, 2], 'Two': [2, 3], 'Three': [3, 4]}

print ("Dictionary of lists : " + str(x))

result = [dict(zip(x, i)) for i in zip(*x.values())]

print ("Final List of dictionaries: " + str(result))

 

Output:

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