Convert Matrix to Coordinate Dictionary in Python


The dictionary is one of the most popular among four datatypes known for unordered collection of key-value pairs. The Python matrix will be used to represent the list of lists whereas an inner list represents the row-value of a matrix. A coordinate dictionary is defined as tuples to set the rows and columns by giving coordinates value. In Python, we have some built-in functions such as len(), range(), zip(), etc. that can be used to solve Convert Matrix to Coordinate dictionary.

Syntax

The following syntax is used in the examples-

len()

The len() is a built-in method in Python that returns the length of the objects.

range()

The range() is a built-in function in Python that returns the sequence of elements between a given range. By default, the initial range always starts with 0 and ends by assigning a specific range.

zip()

The zip() is an in-built function in Python that can be used to combine two or more elements for iterables.

enumerate()

The built-in function enumerate() of Python allows iteration through an orderly sequence to keep track of each index element.

argwhere()

The argwhere() is a built-in method in Python that returns the element indices as non-zero values.

nonzero()

The nonzero() is an in-built function in Python that can be used to find the indices of an array.

Using Nested Loop

In the following example, the program uses a nested-for loop to iterate through the rows and columns. Using an if statement it set the condition as a matrix value not equivalent to zero which satisfies the key containing zero elements as coordinates pair and value pair as non-zero element. Finally, it will use the function return to display the specific result.

Example

def matrix_to_coordinate_dict(matrix):
    coord_dict = {}
    rows = len(matrix)
    cols = len(matrix[0])
    for i in range(rows):
        for j in range(cols):
            value = matrix[i][j]
            if value != 0:
                coord_dict[(i, j)] = value
    return coord_dict

# Create the matrix
my_matrix = [
    [0, 1, 0],
    [2, 0, 3],
    [0, 4, 0]
]
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)

Output

 Conversion of Matrix into Coordinate:
 {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}

Using List Comprehension and enumerate()

In the following example, the program uses dictionary comprehension to iterate over the input matrix. The non-zero element values are added to the coordinate dictionary using rows and columns indexes as keys. Using enumerate() it keeps track of individual element iteration present inside the input matrix. Finally, the function returns the result as key(tuples) and value pairs(non-zero element).

Example

def matrix_to_coordinate_dict(matrix):
    coord_dict = {(i, j): value for i, row in enumerate(matrix) for j, value in enumerate(row) if value != 0}
    return coord_dict

# Create the matrix
my_matrix = [
    [0, 1, 0],
    [2, 0, 3],
    [0, 4, 0]
]
coord_dict = matrix_to_coordinate_dict(my_matrix)
print("Conversion of Matrix into Coordinate:\n", coord_dict)

Output

 Conversion of Matrix into Coordinate:
 {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}

Using Numpy and zip()

In the following example, begin the program with the numpy module and object reference as np. Then use the recursive function to set the conditions and operation based on converting the matrix into a coordinates dictionary. Then it will use dictionary comprehension where it iterates the row and column indices over the input matrix. Next, the function returns the tuple of an array as keys and value pair as a non-zero element and display the result.

Example

import numpy as np

def matrix_to_coordinate_dict(matrix):
    indices = np.nonzero(matrix)
    coord_dict = {(i, j): matrix[i][j] for i, j in zip(indices[0], indices[1])}
    return coord_dict

# Create the matrix
my_matrix = np.array([
    [0, 1, 0],
    [2, 0, 3],
    [0, 4, 0]
])
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)

Output

 {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}

Using Numpy and numpy.argwhere()

In the following example, the program uses a numpy module to set the object reference as np. It uses built-in function argwhere() to find the non-zero element in the matrix. In the resulting dictionary, the key is in the form of tuples to represent the coordinates whereas values are set to non-zero elements of the matrix.

Example

import numpy as np
# Recursive function
def matrix_to_coordinate_dict(matrix):
    indices = np.argwhere(matrix != 0)
    coord_dict = {(i, j): matrix[i][j] for i, j in indices}
    return coord_dict

# Create the matrix
my_matrix = np.array([
    [0, 1, 0],
    [2, 0, 3],
    [0, 4, 0]
])
# Calling function
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)

Output

 {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}

Conclusion

We discussed the various methods to get the solution of converting a matrix to a coordinate dictionary in Python. The coordinates value is represented in the form of tuples where two different integers are set together. There are some applications such as Sparse Matrix Representation, Matrix manipulation, and, Graph Algorithm.

Updated on: 16-Aug-2023

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements