Saturday, December 28, 2024
Google search engine
HomeLanguagesConvert Dictionary Value list to Dictionary List Python

Convert Dictionary Value list to Dictionary List Python

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.

RELATED ARTICLES

Most Popular

Recent Comments