Suppose I have the following numpy.ndarray:
array([[50, 0, 0],
[ 0, 3, 47],
[ 0, 36, 14]])
How is is possible to convert it to a dictionary of this form:
{0: {0: 50}, 1: {1: 3, 2: 47}, 2: {1: 36, 2: 14}}
The question is similar to python 2d array to dict but I cannot work out a solution similar to the answer there no matter how hard I've tried.
Assumed a as your array,
Try this,
{index:{i:j for i,j in enumerate(k) if j} for index,k in enumerate(a)}
Result
{0: {0: 50}, 1: {1: 3, 2: 47}, 2: {1: 36, 2: 14}}
Dictionary created with the concept:
In [18]: dict([[1,'a'],[2,'b']])
Out[18]: {1: 'a', 2: 'b'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With