
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a Matrix to a Dictionary in Python
The matrix is defined by arranging rows and columns to form an array. The values of a matrix in rows and columns either be characters or integers. There are various method names- dictionary comprehension, for loop, enumerate, and, zip() that will be used to Convert a Matrix to a Dictionary in Python.
Using a for Loop and Dictionary Comprehension
The program uses the for loop that will iterate the length of the matrix by applying dictionary comprehension. This helps the conversion of the matrix into a dictionary.
Example
In the following example, we will show the name values of matrix converted into dictionary. The names within each section of the matrix are labeled "Name 1," "Name 2," etc., and the sections individually are labeled "Section 1," "Section 2," etc. Finally, it result the name value matrix into dictionary.
def matrix_to_dict(matrix): dictionary = {f"Section {i+1}": {f"Name {j+1}": matrix[i][j] for j in range(len(matrix[i]))} for i in range(len(matrix))} return dictionary # Matrix input using List matrix = [['Raghav', 'Sunil', 'Kiran', 'Rajendra'], ['Pritam', 'Rahul', 'Mehak', 'Suresh'], ['Tom', 'Peter', 'Mark', 'Jessy']] result = matrix_to_dict(matrix) print(result)
Output
{'Section 1': {'Name 1': 'Raghav', 'Name 2': 'Sunil', 'Name 3': 'Kiran', 'Name 4': 'Rajendra'}, 'Section 2': {'Name 1': 'Pritam', 'Name 2': 'Rahul', 'Name 3': 'Mehak', 'Name 4': 'Suresh'}, 'Section 3': {'Name 1': 'Tom', 'Name 2': 'Peter', 'Name 3': 'Mark', 'Name 4': 'Jessy'}}
Using a Nested for Loop
The program uses a nested for loop that iterates the length of rows and columns and returns the result in the form of dictionary data(rows to set to key and columns set to values.
Example
In the following example, the program convert a matrix into a dictionary. It builds nested dictionaries by repeating the rows and columns. Each matrix component has a label like "row , col" and is connected to the matching value. The matrix data is represented by the dictionary as labeled rows and columns.
def matrix_to_dict(matrix): dictionary = {} for i in range(len(matrix)): row_dict = {} for j in range(len(matrix[i])): row_dict[f"col {j+1}"] = matrix[i][j] dictionary[f"row {i+1}"] = row_dict return dictionary # matrix input matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = matrix_to_dict(matrix) print(result)
Output
{'row 1': {'col 1': 1, 'col 2': 2, 'col 3': 3}, 'row 2': {'col 1': 4, 'col 2': 5, 'col 3': 6}, 'row 3': {'col 1': 7, 'col 2': 8, 'col 3': 9}}
Using Enumerate and Dictionary Comprehension
The program uses enumerates that keeps track of number of iteration in the loop and access the element of that loop. Next, use dictionary comprehension to set the result format of the matrix.
Example
In the following example, begin the program by a recursive function that known for calling the function litself. The use the dictionary comprehension technique by using built-in method enumerate() to store it in the variable dict. Then return the variable dict to get the new transformation of the dictionary. Now create the sublist that represents the matrix and store it in the variable matrix. Then use the calling function that accepts the parameter named matrix to pass its value and store it in the variable result. Finally, we print the output with the help of the result.
def matrix_to_dict(matrix): dict = {f"row {i+1}": {f"column {j+1}": value for j, value in enumerate(row)} for i, row in enumerate(matrix)} return dict # Input of Matrix matrix = [[11, 12, 13], [40, 50, 60], [17, 18, 19],[80, 90, 100]] # Pass the value of the matrix using the recursive function result = matrix_to_dict(matrix) print(result)
Output
{'row 1': {'column 1': 11, 'column 2': 12, 'column 3': 13}, 'row 2': {'column 1': 40, 'column 2': 50, 'column 3': 60}, 'row 3': {'column 1': 17, 'column 2': 18, 'column 3': 19}, 'row 4': {'column 1': 80, 'column 2': 90, 'column 3': 100}}
Using a zip() and Dictionary Comprehension
The program use zip() to set the nested dictionary as a value and set the data in key by using dictionary comprehension i.e. {}.
Example
In the following example, we will use the recursive function named matrix_to_dict fun that accepts the parameter named matrix that has list values. Then it uses a list comprehension to store it in the variable keys. Next, it constructs the dictionary of given key-pair by comprehension technique after going through each row in the matrix and storing it in the variable dictionary. Based on the rows index, each row creates a key using the pattern "SN 1", "SN 2", and so on.
Moving ahead to return dictionary that will calculate the conversion of matrix into dictionary. Now simply create the matrix using sublist and store it in the variable matrix. Then use the calling function to pass the variable matrix and store it in the variable result. Finally, we are printing the output with the help of variable result.
def matrix_to_dict(matrix): keys = [f"Letter {j+1}" for j in range(len(matrix[0]))] # Each key is generated using different dictionary comprehension dictionary = {f"SN {i+1}": {key: value for key, value in zip(keys, row)} for i, row in enumerate(matrix)} return dictionary # Take input as a character matrix using List matrix = [['A', 'B', 'C'], ['P', 'Q', 'R'], ['X', 'Y', 'Z']] result = matrix_to_dict(matrix) print(result)
Output
{'SN 1': {'Letter 1': 'A', 'Letter 2': 'B', 'Letter 3': 'C'}, 'SN 2': {'Letter 1': 'P', 'Letter 2': 'Q', 'Letter 3': 'R'}, 'SN 3': {'Letter 1': 'X', 'Letter 2': 'Y', 'Letter 3': 'Z'}}
Conclusion
We discussed the various method to convert a matrix into a dictionary. All the above outputs show the different dictionary representations by using integers and characters. In conclusion, this conversion allows for a more efficient and flexible representation of data.