Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Numpy Array to Python Dictionary with Sequential Keys?

I have a matrix in the form of a numpy array like this :

myarray = np.array[[0,400,405,411,415,417,418,0]
                   [0,404,412,419,423,422,422,0]
                   [0,409,416,421,424,425,425,0]
                   [0,411,414,417,420,423,426,0]
                   [0,409,410,410,413,419,424,0]
                   [0,405,404,404,409,414,419,0]]

and also empty dictionary :

dict = { }

In my case, i want to convert that array to python dictionary where the keys of dictionary are sequential number calculated from up-left value (myarray[0][0]) until bottom-right value (myarray[5][7]) interleaved by row. So the result will be like this :

dict = { 1 : 0, 2 : 400, 3: 405, ........, 47 : 419 ,48 : 0 } 

is there any solution for this condition? wish for your help.. Any help would be very appreciated..

like image 421
Faizalprbw Avatar asked Jul 22 '15 23:07

Faizalprbw


1 Answers

Use flatten and then create the dictionary with the help of enumerate starting from 1:

myarray = np.array([[0,400,405,411,415,417,418,0],
                   [0,404,412,419,423,422,422,0],
                   [0,409,416,421,424,425,425,0],
                   [0,411,414,417,420,423,426,0],
                   [0,409,410,410,413,419,424,0],
                   [0,405,404,404,409,414,419,0]])

d = dict(enumerate(myarray.flatten(), 1))

Output of d:

{1: 0,
 2: 400,
 3: 405,
 4: 411,
 5: 415,
 6: 417,
 7: 418,
 8: 0,
 9: 0,
 10: 404,
 ...
like image 140
JuniorCompressor Avatar answered Oct 21 '22 09:10

JuniorCompressor