Open In App

Python program to Convert Matrix to List of dictionaries

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix, convert it to a list of dictionaries by mapping similar index values.

Input : test_list = [[“Gfg”, [1, 2, 3]], [“best”, [9, 10, 11]]] 
Output : [{‘Gfg’: 1, ‘best’: 9}, {‘Gfg’: 2, ‘best’: 10}, {‘Gfg’: 3, ‘best’: 11}] 

Input : test_list = [[“Gfg”, [1, 2, 3]]] 
Output : [{‘Gfg’: 1}, {‘Gfg’: 2}, {‘Gfg’: 3}] 

Method #1: The brute way in which this task can be performed is using a loop. In this, we iterate for all the elements in Matrix, and update dictionaries binding keys to appropriate values in dictionary.

Python3




# initializing list
test_list = [["Gfg", [1, 2, 3]],
             ["is", [6, 5, 4]], ["best", [9, 10, 11]]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using loop to bind Matrix elements to dictionary
res = []
for key, val in test_list:
 
    for idx, val in enumerate(val):
 
        # append values according to rows structure
        if len(res) - 1 < idx:
            res.append({key: val})
 
        else:
            res[idx].update({key: val})
 
# printing result
print("Converted dictionary : " + str(res))


Output:

The original list : [[‘Gfg’, [1, 2, 3]], [‘is’, [6, 5, 4]], [‘best’, [9, 10, 11]]] Converted dictionary : [{‘Gfg’: 1, ‘is’: 6, ‘best’: 9}, {‘Gfg’: 2, ‘is’: 5, ‘best’: 10}, {‘Gfg’: 3, ‘is’: 4, ‘best’: 11}]

Method #2: Using Zip and Dictionary Comprehension

Step-by-step algorithm:

  1. Create a list of lists, test_list.
  2. Use the zip function to combine the inner lists of test_list into tuples.
  3. Create a list comprehension that extracts only the lists of integers from test_list and store them in a separate list.
  4. Use another zip function to combine the strings from test_list with the tuples.
  5. Use a list comprehension and dictionary unpacking to create a dictionary for each tuple of strings and integers.
  6. Store the dictionaries in a list, res.
  7. Print the final result.

Below is the implementation of the above approach:

Python3




test_list = [["Gfg", [1, 2, 3]],
             ["is", [6, 5, 4]], ["best", [9, 10, 11]]]
 
 
# printing original list
print("The original list : " + str(test_list))
 
# using zip to combine the inner lists into tuples
zipped = list(zip(*[lst for _, lst in test_list]))
 
# using list comprehension and dictionary unpacking to create the dictionaries
res = [{key: val for key, val in zip([k for k, _ in test_list], tup)} for tup in zipped]
 
# printing result
print("Converted dictionary : " + str(res))


Output

The original list : [['Gfg', [1, 2, 3]], ['is', [6, 5, 4]], ['best', [9, 10, 11]]]
Converted dictionary : [{'Gfg': 1, 'is': 6, 'best': 9}, {'Gfg': 2, 'is': 5, 'best': 10}, {'Gfg': 3, 'is': 4, 'best': 11}]

Time Complexity: O(nm), where n is the number of sub-lists in test_list and m is the length of the longest sub-list.
Auxiliary Space: O(nm), where n is the number of sub-lists in test_list and m is the length of the longest sub-list.

Method #3: Using lambda map dict and zip() inbuilt function

  • Define the input list of lists.
  • Define a lambda function that takes two arguments, one for the key and the other for the value.
  • Use the zip function to combine the sublists into a list of tuples.
  • For each tuple in the list of tuples, use the map function to apply the lambda function to the corresponding key and value.
  • Use the dict function to convert the resulting list of tuples into a dictionary.
  • Combine the dictionaries into a list using the list function.

Python3




# initializing list
test_list = [["Gfg", [1, 2, 3]],
            ["is", [6, 5, 4]], ["best", [9, 10, 11]]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using zip to combine the inner lists into tuples
zipped = list(zip(*[lst for _, lst in test_list]))
 
# using lambda function and zip function to create the dictionaries
res = [dict(zip(map(lambda x: x[0], test_list), tup)) for tup in zipped]
 
# printing result
print("Converted dictionary : " + str(res))


Output

The original list : [['Gfg', [1, 2, 3]], ['is', [6, 5, 4]], ['best', [9, 10, 11]]]
Converted dictionary : [{'Gfg': 1, 'is': 6, 'best': 9}, {'Gfg': 2, 'is': 5, 'best': 10}, {'Gfg': 3, 'is': 4, 'best': 11}]

Time Complexity: O(nm), where n is the number of sub-lists in test_list and m is the length of the longest sub-list.
Auxiliary Space: O(nm), where n is the number of sub-lists in test_list and m is the length of the longest sub-list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads