Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert Matrix to Coordinate Dictionary in Python
A coordinate dictionary is a dictionary where keys are tuples representing (row, column) positions and values are the non-zero elements from a matrix. This conversion is useful for sparse matrix representation where most elements are zero.
Syntax
The following built-in functions are commonly used for matrix to coordinate dictionary conversion ?
len(object) # Returns length of an object range(start, stop) # Returns sequence of numbers enumerate(iterable) # Returns index and value pairs zip(*iterables) # Combines multiple iterables
For NumPy operations ?
np.nonzero(array) # Returns indices of non-zero elements np.argwhere(condition)# Returns indices where condition is True
Using Nested Loops
The most straightforward approach uses nested loops to iterate through rows and columns, adding non-zero elements to the dictionary ?
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("Coordinate Dictionary:", coord_dict)
Coordinate Dictionary: {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
Using List Comprehension with enumerate()
A more Pythonic approach using dictionary comprehension and enumerate() to track indices ?
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("Coordinate Dictionary:", coord_dict)
Coordinate Dictionary: {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
Using NumPy nonzero() and zip()
NumPy provides efficient methods for finding non-zero elements using nonzero() ?
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("Coordinate Dictionary:", coord_dict)
Coordinate Dictionary: {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
Using NumPy argwhere()
The argwhere() function directly returns coordinate pairs where a condition is met ?
import numpy as np
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]
])
coord_dict = matrix_to_coordinate_dict(my_matrix)
print("Coordinate Dictionary:", coord_dict)
Coordinate Dictionary: {(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
Comparison
| Method | Best For | Performance | Memory Usage |
|---|---|---|---|
| Nested Loops | Simple cases, learning | Moderate | Low |
| List Comprehension | Pure Python, readability | Good | Low |
| NumPy nonzero() | Large matrices | Excellent | Moderate |
| NumPy argwhere() | Complex conditions | Excellent | Moderate |
Conclusion
Converting matrices to coordinate dictionaries is essential for sparse matrix operations. Use list comprehension for pure Python solutions or NumPy methods for better performance with large matrices. This technique is widely used in graph algorithms and sparse matrix representations.
