Open In App

Python – Key Columns Dictionary from Matrix

Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix and list of keys, map each column’s values with a custom list key.

Input : test_list1 = [[4, 6], [8, 6]], test_list2 = ["Gfg", "Best"] 
Output : {'Gfg': [4, 8], 'Best': [6, 6]} 
Explanation : Column wise, Key values assignment.
Input : test_list1 = [[4], [6]], test_list2 = ["Gfg"] 
Output : {'Gfg': [4, 6]} 
Explanation : Column wise, Key values assignment, just single element list.  

Method #1 : Using list comprehension + dictionary comprehension

The combination of the above functionality can be used to solve this problem. In this, we perform the task of extracting column values using list comprehension, and then dictionary comprehension is used to form a dictionary with list keys.

Python3




# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
# Using list comprehension + dictionary comprehension
 
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# dictionary comprehension to compile result
# using enumerate to get column numbers
res = {key: [sub[idx] for sub in test_list1]
       for idx, key in enumerate(test_list2)}
 
# printing result
print("The paired dictionary : " + str(res))


Output

The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': [4, 8, 8], 'is': [6, 4, 6], 'Best': [8, 2, 3]}

Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements

Method #2 : Using zip() + dict()

This is yet another way in which this task can be performed. In this, we join key-value pair using zip() and dict() is used to convert result in the dictionary. The difference is that it generates tuples rather than lists as mapped values.

Python3




# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
# Using zip() + dict()
 
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# zip() used to map keys with values and return tuples
# as result
# * operator used to perform unpacking
res = dict(zip(test_list2, zip(*test_list1)))
 
# printing result
print("The paired dictionary : " + str(res))


Output

The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': (4, 8, 8), 'is': (6, 4, 6), 'Best': (8, 2, 3)}

Method #3: Using nested loops

  1. Initiate a nested for loop to access a list of lists(test_list1) column-wise and create a new list of lists(v) with elements column wise
  2. Initiate another for loop to create a dictionary with test_list2(list of strings)elements as keys and columns list as values
  3. Display the dictionary

Python3




# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
 
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
x = []
 
res = dict()
 
for i in range(0, len(test_list1)):
    v = []
    for j in range(0, len(test_list1[i])):
        v.append(test_list1[j][i])
    x.append(v)
     
for i in range(0, len(test_list2)):
    res[test_list2[i]] = x[i]
 
# printing result
print("The paired dictionary : " + str(res))


Output

The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': [4, 8, 8], 'is': [6, 4, 6], 'Best': [8, 2, 3]}

Time Complexity: O(M*N) , M is the length of list of lists, N – length of the list
Auxiliary Space: O(M) , M – length of dictionary

Method #4: Using NumPy

This approach uses NumPy’s transpose() function to extract the columns from the matrix and then creates a dictionary using the elements of the given list as keys and the extracted columns as values. This method is efficient and requires less code.

Python3




import numpy as np
 
# Initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
 
# Printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using NumPy's transpose() function
cols = np.transpose(test_list1)
 
# Creating dictionary
res = dict(zip(test_list2, cols))
 
# Printing result
print("The paired dictionary : " + str(res))


OUTPUT : 
The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': array([4, 8, 8]), 'is': array([6, 4, 6]), 'Best': array([8, 2, 3])}

The time and auxiliary space complexity of this method is O(n^2) where n is the length of the matrix.

 Method #5: Using a nested list comprehension and the zip() function

Steps:

  1. Initialize two lists test_list1 and test_list2
  2. Print the original lists using print() function
  3. Using zip() function with *args argument to transpose the matrix, creating a list of tuples with elements of the same index from each list.
  4. Using a dictionary comprehension and enumerate() to assign each element of test_list2 as a key to each tuple of the transposed matrix in test_list1.
  5. Print the resulting dictionary using the print() function.

Python3




# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using a nested list comprehension and the zip function to compile result
res = {test_list2[i]: list(col) for i, col in enumerate(zip(*test_list1))}
 
# printing result
print("The paired dictionary : " + str(res))


Output

The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': [4, 8, 8], 'is': [6, 4, 6], 'Best': [8, 2, 3]}

Time Complexity: O(N*M), where N is the number of lists in the test_list1 and M is the length of each list in the test_list1. This is because we must iterate through each element in each list in test_list1 in order to transpose it.

Auxiliary Space: O(NM), where N is the number of lists in test_list1 and M is the length of each list in test_list1. This is because we create a new list with the transposed matrix, which will have NM elements. Additionally, we create a dictionary with N keys and M values each, resulting in N*M total elements.



Last Updated : 08 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads