Python – Key Columns Dictionary from Matrix
Last Updated :
08 May, 2023
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
test_list1 = [[ 4 , 6 , 8 ], [ 8 , 4 , 2 ], [ 8 , 6 , 3 ]]
test_list2 = [ "Gfg" , "is" , "Best" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = {key: [sub[idx] for sub in test_list1]
for idx, key in enumerate (test_list2)}
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
test_list1 = [[ 4 , 6 , 8 ], [ 8 , 4 , 2 ], [ 8 , 6 , 3 ]]
test_list2 = [ "Gfg" , "is" , "Best" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = dict ( zip (test_list2, zip ( * test_list1)))
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
- 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
- Initiate another for loop to create a dictionary with test_list2(list of strings)elements as keys and columns list as values
- Display the dictionary
Python3
test_list1 = [[ 4 , 6 , 8 ], [ 8 , 4 , 2 ], [ 8 , 6 , 3 ]]
test_list2 = [ "Gfg" , "is" , "Best" ]
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]
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
test_list1 = [[ 4 , 6 , 8 ], [ 8 , 4 , 2 ], [ 8 , 6 , 3 ]]
test_list2 = [ "Gfg" , "is" , "Best" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
cols = np.transpose(test_list1)
res = dict ( zip (test_list2, cols))
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:
- Initialize two lists test_list1 and test_list2
- Print the original lists using print() function
- Using zip() function with *args argument to transpose the matrix, creating a list of tuples with elements of the same index from each list.
- 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.
- Print the resulting dictionary using the print() function.
Python3
test_list1 = [[ 4 , 6 , 8 ], [ 8 , 4 , 2 ], [ 8 , 6 , 3 ]]
test_list2 = [ "Gfg" , "is" , "Best" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = {test_list2[i]: list (col) for i, col in enumerate ( zip ( * test_list1))}
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.
Similar Reads
Count the Key from Nested Dictionary in Python
In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
4 min read
Python - Convert Matrix to Dictionary
The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
4 min read
Python - Columns to Dictionary Conversion in Matrix
Given a Matrix, Convert to Dictionary with elements in 1st row being keys, and subsequent rows acting as values list. Input : test_list = [[4, 5, 7], [10, 8, 4], [19, 4, 6], [9, 3, 6]] Output : {4: [10, 19, 9], 5: [8, 4, 3], 7: [4, 6, 6]} Explanation : All columns mapped with 1st row elements. Eg. 4
3 min read
Python - Column Maximum in Dictionary Value Matrix
Given a Dictionary with Matrix Values, compute maximum of each column of those Matrix. Input : test_dict = {"Gfg" : [[7, 6], [3, 2]], "is" : [[3, 6], [6, 10]], "best" : [[5, 8], [2, 3]]} Output : {'Gfg': [7, 6], 'is': [6, 10], 'best': [5, 8]} Explanation : 7 > 3, 6 > 2, hence ordering. Input :
5 min read
Remove Kth Key from Dictionary - Python
We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python - Remove Multiple Keys from Dictionary
We are given a dictionary and our task is to remove multiple keys from the dictionary. For example, consider a dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} where we want to remove the keys 'b' and 'd', then the output will be {'a': 1, 'c': 3}. Let's explore different methods to remove multiple ke
3 min read
Python - Custom order dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the custom ordering of keys of dictionary. This is quite popular problem, with the advent of newer version of Python, where keys are ordered in Dictionaries, there might be requirement to reorder dic
3 min read
Dictionary keys as a list in Python
In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
2 min read
Get all Tuple Keys from Dictionary - Python
In Python, dictionaries can have tuples as keys which is useful when we need to store grouped values as a single key. Suppose we have a dictionary where the keys are tuples and we need to extract all the individual elements from these tuple keys into a list. For example, consider the dictionary : d
3 min read
Convert Matrix to Dictionary Value List - Python
We are given a matrix and the task is to map each column of a matrix to customized keys from a list. For example, given a matrix li = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]] and a list map_li = [4, 5, 6], the goal is to map the first column to the key 4, the second column to the key 5, and the
3 min read