How to store a sparse matrix non zero values and indexes in a dictionary in Python

1 Answer

0 votes
matrix = [[0,19,0,0,0],
          [0,17,0,13,0],
          [0,0,14,0,0]]

Dict={}
    
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] != 0:
            Dict[i, j] = matrix[i][j]
    
print(Dict)
    
    
    

'''
run:

{(0, 1): 19, (1, 1): 17, (1, 3): 13, (2, 2): 14}

'''

 



answered Oct 3, 2021 by avibootz
...