Reputation: 313
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.
Upvotes: 3
Views: 2243
Reputation: 175
This function should work for a 2-D array and 1-D array as well. Additionally you can make it work for list with int/float just by commenting the first line of the function.
def arrtodict(your_array):
your_array = your_array.tolist()
dict_data = {key: value for key, value in enumerate(your_array)}
if type(dict_data[0]) is list:
for key, value in dict_data.items():
dict_data[key] = {k: v for k, v in enumerate(value)}
elif type(dict_data[0]) is (float or int):
pass
else:
print ('Check Your data')
return dict_data
Upvotes: 0
Reputation: 16081
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'}
Upvotes: 5
Reputation: 55489
You can do that with a pair of nested for
loops.
The built-in enumerate
function steps through a list or other iterable, giving us both the item and its index.
import numpy as np
a = np.array(
[[50, 0, 0],
[ 0, 3, 47],
[ 0, 36, 14]]
)
d = {}
for i, row in enumerate(a):
temp = {}
for j, v in enumerate(row):
if v:
temp[j] = v
d[i] = temp
print(d)
output
{0: {0: 50}, 1: {1: 3, 2: 47}, 2: {1: 36, 2: 14}}
That can be condensed considerably by using a nested pair of dictionary comprehensions:
d = {i: {j: v for j, v in enumerate(row) if v}
for i, row in enumerate(a)}
Upvotes: 2
Reputation: 1289
Just loop through and build your nested dicts
:
import numpy as np
arr = np.array([[50, 0, 0],
[ 0, 3, 47],
[ 0, 36, 14]])
d = {}
for i, row in enumerate(arr):
d[i] = {}
for j, cell in enumerate(row):
if cell != 0:
d[i][j] = cell
Upvotes: 1