Python – Convert Matrix to dictionary
Last Updated :
14 Mar, 2023
Given a Matrix, convert it into dictionary with keys as row number and value as nested list.
Input : test_list = [[5, 6, 7], [8, 3, 2]] Output : {1: [5, 6, 7], 2: [8, 3, 2]} Explanation : Matrix rows are paired with row number in order. Input : test_list = [[5, 6, 7]] Output : {1: [5, 6, 7]} Explanation : Matrix rows are paired with row number in order.
Method #1 : Using dictionary comprehension + range()
The combination of above functions can be used to solve this problem. In this, we perform the task of iteration using dictionary comprehension and range() can be used to perform numbering of rows.
Python3
test_list = [[ 5 , 6 , 7 ], [ 8 , 3 , 2 ], [ 8 , 2 , 1 ]]
print ( "The original list is : " + str (test_list))
res = {idx + 1 : test_list[idx] for idx in range ( len (test_list))}
print ( "The constructed dictionary : " + str (res))
|
Output
The original list is : [[5, 6, 7], [8, 3, 2], [8, 2, 1]]
The constructed dictionary : {1: [5, 6, 7], 2: [8, 3, 2], 3: [8, 2, 1]}
Time Complexity: O(n) where n is the number of elements in the list test_list.
Auxiliary Space: O(n), where n is the number of elements in the list test_list.
Method #2 : Using dictionary comprehension + enumerate()
The combination of above functions can be used to solve this problem. In this, dictionary comprehension help in construction of dictionary and enumerate() helps in iteration like range() in above method.
Python3
test_list = [[ 5 , 6 , 7 ], [ 8 , 3 , 2 ], [ 8 , 2 , 1 ]]
print ( "The original list is : " + str (test_list))
res = {idx: val for idx, val in enumerate (test_list, start = 1 )}
print ( "The constructed dictionary : " + str (res))
|
Output
The original list is : [[5, 6, 7], [8, 3, 2], [8, 2, 1]]
The constructed dictionary : {1: [5, 6, 7], 2: [8, 3, 2], 3: [8, 2, 1]}
Please Login to comment...