Open In App

Convert Dictionary Value list to Dictionary List Python

Last Updated : 24 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using loop
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using loop
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
         
# printing result
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




# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]},
             {'is' : [10, 2, 3]},
             {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
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]
 
# printing result
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:

  1. Initialize a list test_list with three dictionaries, where each dictionary has a single key-value pair.
  2. Print the original list using the print() function and string concatenation with str().
  3. Initialize a list res with empty dictionaries, where the number of dictionaries is equal to the length of test_list.
  4. 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.
  5. Print the result using the print() function and string concatenation with str().

Python3




# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using loop
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
 
# printing result
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




# initializing list
test_list = [{'Gfg' : [5, 6, 5]},
             {'is' : [10, 2, 3]},
             {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using dictionary comprehension and map()
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]))]
 
# printing result
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
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List using defaultdict
res = defaultdict(list)
for d in test_list:
    for key, val in d.items():
        res[key].extend(val)
 
# Convert the defaultdict to a list of dictionaries
res = [dict(zip(res.keys(), x)) for x in zip(*res.values())]
 
# printing result
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

  1. Define a function dict_val_to_list that takes test_list, idx (optional with default 0), and res (optional with default None) as arguments.
  2. If res is None, initialize res as a list of dictionaries with the same length as test_list.
  3. If idx is greater than or equal to the length of test_list, return res.
  4. Iterate over key-value pairs in the dictionary at index idx of test_list.
  5. Iterate over values in the current value list.
  6. Update the dictionary at the current index of res with the current key and value.
  7. Make a recursive call to dict_val_to_list with the next index of test_list and the updated res.
  8. Return res.

Python3




# Python program for the above approach
 
# Function to convert the dictionary
# value to list
def dict_val_to_list(test_list, idx=0, res=None):
   
    # initialize result list on first call
    if res is None:
        res = [{} for _ in range(len(test_list))]
 
    # base case: reached end of list
    # of dictionaries
    if idx >= len(test_list):
        return res
 
    # iterate over key-value pairs in
    # the current dictionary
    for key, val in test_list[idx].items():
       
        # iterate over values in the
        # current value list
        for i, ele in enumerate(val):
           
            # update the result dictionary
            # with current key and value
            res[i][key] = ele
 
        # recursive call to process next
        # dictionary in the list
        dict_val_to_list(test_list, idx+1, res)
 
    return res
 
# Driver Code
 
test_list = [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
 
# Print the original list
print("The original list is : " + str(test_list))
 
res = dict_val_to_list(test_list)
 
# Print the result
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.



Similar Reads

Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 min read
Python - Convert list to Single Dictionary Key Value list
Sometimes, while working with Python lists, we can have a problem in which we need to convert the list into a dictionary, which has single key, the Kth element of list, and others as its list value. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [6, 5,
7 min read
Python - Convert list of dictionaries to Dictionary Value list
Given a list of dictionary, convert to dictionary with same key mapped with all values in as value list. Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}] Output : {'Gfg': [6, 8], 'is': [9, 11], 'best': [10, 19]} Explanation : 6, 8 of "Gfg" mapped as value list, similarly every other. Input : test_list =
10 min read
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with respective rest of words as list. Input : test_li
8 min read
Python | Convert list of tuples to dictionary value lists
One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st elements of tuple, which are uniquely identified as keys in dictionary and it's corresponding value as a list of the corresponding value of respective keys as tuple's second element. Let's discuss how to solve
9 min read
Python - Convert List to Index and Value dictionary
Given a List, convert it to dictionary, with separate keys for index and values. Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = "1", "2" Output : {'1': [0, 1, 2, 3, 4, 5, 6], '2': [3, 5, 7, 8, 2, 4, 9]} Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2". Input : test_list = [3, 5, 7], idx, val = "1", "2" Ou
3 min read
Python - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4 Output : {4: (4, 5), 5: (1, 3), 6:
4 min read
Python Program to convert Dictionary to List by Repeating keys corresponding value times
Given a dictionary where keys are characters and their constituent values are numbers, the task here is to write a python program that can convert it to a list by repeating the key character value times. Input : test_dict = {'g' : 2, 'f' : 3, 'g' : 1, 'b' : 4, 'e' : 1, 's' : 4, 't' : 3}Output : ['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's'
6 min read
Python program to Convert Matrix to Dictionary Value List
Given Matrix, the task is to write a Python program to map each column's values as customized keys from another list. Input : test_list = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]], map_list = [4, 5, 6]Output : {4: [4, 1, 3, 10], 5: [5, 3, 8, 3], 6: [6, 5, 1, 5]}Explanation : 4 is mapped with all the 0th index of lists, 4, 1 ,3, 10. Input : test
4 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Practice Tags :
three90RightbarBannerImg