9

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..

1
  • Flatten it and zip it with numpy.arange(), pass the zipped structure to dict(). Commented Jul 22, 2015 at 23:26

1 Answer 1

20

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,
 ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.