Assume the next dictionary is given:
JavaScript
x
2
1
{(0, 0): 1, (1, 1): 12, (2, 2): 802, (3, 3): 1687, (4, 4): 11, (5, 4): 4, (6, 5): 593, (7, 4): 4}
2
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:
JavaScript
1
9
1
array([[ 1, 0, 0, 0, 0, 0],
2
[ 0, 12, 0, 0, 0, 0],
3
[ 0, 0, 802, 0, 0, 0],
4
[ 0, 0, 0, 1687, 0, 0],
5
[ 0, 0, 0, 0, 11, 0],
6
[ 0, 0, 0, 0, 4, 0],
7
[ 0, 0, 0, 0, 0, 593],
8
[ 0, 0, 0, 0, 4, 0]])
9
Advertisement
Answer
You could use np.add.at
, defining the shape of the array beforehand from the keys:
JavaScript
1
17
17
1
d = {(0, 0): 1, (1, 1): 12, (2, 2): 802, (3, 3): 1687, (4, 4): 11,
2
(5, 4): 4, (6, 5): 593, (7, 4): 4}
3
4
i,j = zip(*d.keys())
5
a = np.zeros((max(i)+1,max(j)+1), np.int32)
6
np.add.at(a, tuple((i,j)), tuple(d.values()))
7
8
a
9
array([[ 1, 0, 0, 0, 0, 0],
10
[ 0, 12, 0, 0, 0, 0],
11
[ 0, 0, 802, 0, 0, 0],
12
[ 0, 0, 0, 1687, 0, 0],
13
[ 0, 0, 0, 0, 11, 0],
14
[ 0, 0, 0, 0, 4, 0],
15
[ 0, 0, 0, 0, 0, 593],
16
[ 0, 0, 0, 0, 4, 0]])
17