Python - Convert Matrix to Coordinate Dictionary

Python - Convert Matrix to Coordinate Dictionary

Converting a matrix (2D list) into a coordinate dictionary means that we'll represent each element in the matrix by its coordinates (i, j) as the key and the value at that coordinate as the value in the dictionary.

Given:

A matrix:

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

Desired Outcome:

A dictionary with coordinate tuples (i, j) as keys and the corresponding matrix values as dictionary values:

{
    (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
}

Tutorial:

1. Nested Loop Iteration:

Iterate over each row and each element in the row using nested loops.

2. Create a Dictionary:

For each element of the matrix, store its value in the dictionary using its coordinates (i, j) as the key.

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

3. Print the Result:

print(coords_dict)

Full Code:

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

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

Output:

{
    (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
}

Notes:

  • This method assumes that the matrix is a 2D list where all rows have the same number of columns.
  • The dictionary will have as many key-value pairs as there are elements in the matrix. If the matrix is very large, the resulting dictionary could consume a significant amount of memory.

More Tags

gcloud horizontal-scrolling glob use-effect cloudflare mobile-application confusion-matrix flutter-doctor compiler-errors expression-trees

More Programming Guides

Other Guides

More Programming Examples