Convert Dictionary Value list to Dictionary List Python
Last Updated :
24 Jun, 2023
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains.
Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘Gfg’: [5, 6]}, {‘best’: [3, 1]}]
Output : [{‘Gfg’: 5, ‘best’: 3}, {‘Gfg’: 6, ‘best’: 1}]
Input : test_list = [{‘Gfg’: [5]}]
Output : [{‘Gfg’: 5}]
Convert Dictionary Value list to Dictionary Using loop
This is one of the ways in which this problem can be solved. In this, we perform the task in brute force manner iterating each list value index and designating a key to it.
Step-by-step approach:
- Create an empty list res that will hold the converted dictionaries.
- Initialize idx to 0. This variable will be used to track the index of the current dictionary in res.
- Loop through each dictionary in test_list.
- For each dictionary in test_list, loop through each key-value pair using the items() method.
- For each value in the current key-value pair, loop through the elements of the list using a for loop.
- For each element in the list, assign a new dictionary to res[idx] where the key is the current key and the value is the current element.
- Increment the idx variable to move on to the next dictionary in res.
- Reset idx to 0, since we only want one key-value pair in each dictionary in res.
- Print the converted list using the print() function.
Below is the implementation of the above approach:
Python3
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]}, { 'is' : [ 10 , 2 , 3 ]}, { 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
res = [{} for idx in range ( len (test_list))]
idx = 0
for sub in test_list:
for key, val in sub.items():
for ele in val:
res[idx][key] = ele
idx + = 1
idx = 0
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]
Time Complexity: O(n)
Auxiliary Space: O(n)
Convert Dictionary Value list to Dictionary Using list comprehension + zip()
This is yet another way in which we can perform this task. In this, we perform task in 2 steps, first, we extract all the keys and then pair up values using zip() accordingly.
Python3
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]},
{ 'is' : [ 10 , 2 , 3 ]},
{ 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
keys = [ list (sub.keys())[ 0 ] for sub in test_list]
vals = zip ( * [val for sub in test_list for val in sub.values()])
res = [ dict ( zip (keys, val)) for val in vals]
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'b...
Time complexity: O(nm), where n is the length of the original list and m is the length of the value list in each dictionary.
Auxiliary space: O(nm).
Convert Dictionary Value list to Dictionary Using loop + enumerate()
Use a loop to iterate over the original list of dictionaries and extract the key-value pairs from each dictionary. It then assigns each value to the corresponding dictionary in the result list.
step-by-step approach of the program:
- Initialize a list test_list with three dictionaries, where each dictionary has a single key-value pair.
- Print the original list using the print() function and string concatenation with str().
- Initialize a list res with empty dictionaries, where the number of dictionaries is equal to the length of test_list.
- Iterate over the test_list using a for loop with the enumerate() function. For each dictionary d in test_list:
Get the key-value pair of the dictionary as a list of tuples using the items() method, then get the first tuple in the list using indexing [0].
Assign the key to the variable key and the value to the variable val.
Iterate over the values in val using another for loop with the enumerate() function. For each value v in val:
Assign the value of v to the corresponding key in res using indexing.
- Print the result using the print() function and string concatenation with str().
Python3
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]}, { 'is' : [ 10 , 2 , 3 ]}, { 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
res = [{} for i in range ( len (test_list))]
for i, d in enumerate (test_list):
key, val = list (d.items())[ 0 ]
for j, v in enumerate (val):
res[j][key] = v
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]
Time complexity: O(n*m), where n is the length of the original list and m is the length of the value list in each dictionary.
Auxiliary space: O(n*m).
Convert Dictionary Value list to Dictionary Using Dictionary comprehension + map()
The program achieves this using a dictionary comprehension and the built-in function map(). The map() function is used to extract the key-value pairs from each dictionary in the input list. The dictionary comprehension is used to create a new dictionary with the extracted key-value pairs. We iterate over the length of the value list in the first dictionary in the input list to ensure that we create a dictionary for each element in the value list.
Python3
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]},
{ 'is' : [ 10 , 2 , 3 ]},
{ 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
res = [{k: v[i] for k, v in map ( lambda x: ( list (x.keys())[ 0 ],
list (x.values())[ 0 ]),
test_list)} for i in range ( len ( list (test_list[ 0 ].values())[ 0 ]))]
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]
Convert Dictionary Value list to Dictionary Using the defaultdict function
Python3
from collections import defaultdict
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]}, { 'is' : [ 10 , 2 , 3 ]}, { 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
res = defaultdict( list )
for d in test_list:
for key, val in d.items():
res[key].extend(val)
res = [ dict ( zip (res.keys(), x)) for x in zip ( * res.values())]
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]
Time complexity: O(nm), where n is the length of the input list and m is the maximum length of the value lists in the input dictionaries.
Auxiliary space: O(nm), as we are creating a defaultdict and a list of dictionaries.
Convert Dictionary Value list to Dictionary Using the Recursive method
- Define a function dict_val_to_list that takes test_list, idx (optional with default 0), and res (optional with default None) as arguments.
- If res is None, initialize res as a list of dictionaries with the same length as test_list.
- If idx is greater than or equal to the length of test_list, return res.
- Iterate over key-value pairs in the dictionary at index idx of test_list.
- Iterate over values in the current value list.
- Update the dictionary at the current index of res with the current key and value.
- Make a recursive call to dict_val_to_list with the next index of test_list and the updated res.
- Return res.
Python3
def dict_val_to_list(test_list, idx = 0 , res = None ):
if res is None :
res = [{} for _ in range ( len (test_list))]
if idx > = len (test_list):
return res
for key, val in test_list[idx].items():
for i, ele in enumerate (val):
res[i][key] = ele
dict_val_to_list(test_list, idx + 1 , res)
return res
test_list = [{ 'Gfg' : [ 5 , 6 , 5 ]}, { 'is' : [ 10 , 2 , 3 ]}, { 'best' : [ 4 , 3 , 1 ]}]
print ( "The original list is : " + str (test_list))
res = dict_val_to_list(test_list)
print ( "Records after conversion : " + str (res))
|
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]
Time Complexity: O(N*M) where N is the length of test_list and M is the maximum length of the value lists in the dictionaries.
Space Complexity: O(N*M) for the output list of dictionaries.
Please Login to comment...