3

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.

1
  • This is called converting a sparse 2D array to a nested dict of COO (coordinate) format: {i: {j: value}} Commented Mar 22, 2017 at 12:01

4 Answers 4

5

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

1 Comment

Would be more readable with dict comprehensions IMO: {index:{i:j for i,j in enumerate(k) if j} for index,k in enumerate(a)}
2

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)}

Comments

1

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

Comments

0

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

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.