Change language

Python | Split a dictionary of lists into a list of dictionaries

| |

Let’s discuss some methods by which a list dictionary can be converted into a corresponding list of dictionaries.

Method # 1: Using a list comprehension
We can use a list understanding as a one-line alternative for performing various naive tasks providing readability with more concise code. We can iterate over each of the dictionary elements and build the dictionary list accordingly.

# Python3 demo code
# convert the list dictionary to
# list of dictionaries
# use comprehension list

 
# initializing dictionary

test_dict = { "Rash" : [ 1 , 3 ], "Manjeet" : [ 1 , 4 ], "Akash" : [ 3 , 4 ]}

 
# print original dictionary

print ( " The original dictionary is: " + str (test_dict))

 
# using the comprehension list
# convert the list dictionary to
# list of dictionaries

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

for i in range ( 2 )]

 
# print result

print ( "The converted list of dictionaries" +   str (res))

Exit :

The original dictionary is: {’Rash’: [1, 3], ’Manjeet’: [1, 4], ’Akash’: [ 3, 4]}
The converted list of dictionaries [{’Rash’: 1, ’Manjeet’: 1, ’Akash’: 3}, {’Rash’: 3, ’Manjeet’: 4, ’Akash ’: 4}]

Method # 2: Using zip ()
This approach has used the zip function two times, the first time we need to compress a specific index value of all lists as one and two, to get all the values ​​of a specific index and compress it with the appropriate keys.

# Python3 demo code
# convert a list dictionary to
# a list of dictionaries
# using zip ()

 
# initializing dictionary

test_dict = { "Rash" : [ 1 , 3 ], "Manjeet" : [ 1 , 4 ], "Akash" : [ 3 , 4 ]}

 
# printing the original dictionary

print ( "The original dictionary is:" + str (test_dict))

 
# using zip ()
# convert the list dictionary to
# list of dictionaries

res = [ dict ( zip (test_dict, i)) for i in zip ( * test_dict.values ​​())]

 
# print result

print ( "The converted list of dictionaries" +   str (res))

Output:

The original dictionary is: {’Rash’: [1, 3], ’Akash’: [3, 4], ’Manjeet’: [1, 4]}
The converted list of dictionaries [{’Rash’: 1, ’Akash’: 3, ’Manjeet’ : 1}, {’Rash’: 3, ’Akash’: 4, ’Manjeet’: 4}]