Python - Convert Matrix to dictionary

Python - Convert Matrix to dictionary

If you want to convert a matrix (2D list) into a dictionary, you must decide on the structure of the dictionary. There are several ways to represent a matrix as a dictionary.

In this tutorial, we'll consider two approaches:

  1. Using tuple coordinates (i, j) as keys and the matrix values as dictionary values.
  2. Using row indices as keys and the entire row (list) as values.

Given:

A matrix:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

Approach 1: Tuple Coordinates as Keys

Desired Outcome:

{ (0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9 } 

Code:

coords_dict = {(i, j): matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i]))} print(coords_dict) 

Approach 2: Row Indices as Keys

Desired Outcome:

{ 0: [1, 2, 3], 1: [4, 5, 6], 2: [7, 8, 9] } 

Code:

row_dict = {i: matrix[i] for i in range(len(matrix))} print(row_dict) 

Full Tutorial Code:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Approach 1 coords_dict = {(i, j): matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i]))} print("Approach 1:", coords_dict) # Approach 2 row_dict = {i: matrix[i] for i in range(len(matrix))} print("Approach 2:", row_dict) 

Notes:

  • The chosen approach depends on your application and how you plan to access or modify the matrix data in the future.
  • There are other possible structures for representing matrices as dictionaries; the best approach depends on the specific requirements of your task.

More Tags

angular-material-table blink mplot3d amazon-athena sqflite apollo stacked-chart keycloak-services ckeditor error-checking

More Programming Guides

Other Guides

More Programming Examples