How can I convert a Numpy array to a Python dictionary with sequential keys?
I have a matrix as 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 an empty dictionary:
dict = { }
In my case, I want to convert this array to a python dictionary, where the dictionary keys are a sequential number calculated over the left value ( myarray[0][0]
), while the bottom right value ( myarray[5][7]
) is alternated line by line. 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 your help .. Any help would be much appreciated.
+3
source to share
1 answer
Use flatten
and then create a dictionary with enumerate
starting at 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))
Conclusion d
:
{1: 0,
2: 400,
3: 405,
4: 411,
5: 415,
6: 417,
7: 418,
8: 0,
9: 0,
10: 404,
...
+7
source to share