Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2D numpy.ndarray to nested dictionary

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.

like image 561
Nicholas Avatar asked Sep 26 '26 03:09

Nicholas


1 Answers

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'}
like image 153
Rahul K P Avatar answered Sep 27 '26 17:09

Rahul K P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!