Convert dictionary with coordinates and values to 2D array

Tags: ,



Assume the next dictionary is given:

{(0, 0): 1, (1, 1): 12, (2, 2): 802, (3, 3): 1687, (4, 4): 11, (5, 4): 4, (6, 5): 593, (7, 4): 4}

In the dictionary above each key displays a point in the matrix (x, y) and a value displays the value found in the matrix. How could I construct an array that will contain the values located at each point x, y?

According to the dictionary above the expected result is:

array([[   1,    0,    0,    0,    0,    0],
       [   0,   12,    0,    0,    0,    0],
       [   0,    0,  802,    0,    0,    0],
       [   0,    0,    0, 1687,    0,    0],
       [   0,    0,    0,    0,   11,    0],
       [   0,    0,    0,    0,    4,    0],
       [   0,    0,    0,    0,    0,  593],
       [   0,    0,    0,    0,    4,    0]])

Answer

You could use np.add.at, defining the shape of the array beforehand from the keys:

d = {(0, 0): 1, (1, 1): 12, (2, 2): 802, (3, 3): 1687, (4, 4): 11, 
     (5, 4): 4, (6, 5): 593, (7, 4): 4}

i,j = zip(*d.keys())
a = np.zeros((max(i)+1,max(j)+1), np.int32)
np.add.at(a, tuple((i,j)), tuple(d.values()))

a
array([[   1,    0,    0,    0,    0,    0],
       [   0,   12,    0,    0,    0,    0],
       [   0,    0,  802,    0,    0,    0],
       [   0,    0,    0, 1687,    0,    0],
       [   0,    0,    0,    0,   11,    0],
       [   0,    0,    0,    0,    4,    0],
       [   0,    0,    0,    0,    0,  593],
       [   0,    0,    0,    0,    4,    0]])


Source: stackoverflow