Let b
be a dict with some values :
b = {}
b[90, 1] = 100, b[90, 55] = 101, b[90, 127] = 102
b[70, 1] = 40, b[70, 45] = 41, b[70, 107] = 42
How to, in one pass, populate a dict
with its missing values as nearest neighbour, for example for 0 <= i <= 127
, 0 <= j <= 127
?
(it will give 16384 keys in the dict, so that's ok for my application).
As an example, I would like b[73, 40] = b[70, 45] = 41
, i.e.nearest neighboor in a 2D plane.
Here is what I tried :
for i in range(127):
for j in range(127):
closest_key = min(b.keys(), key=lambda c: (c[0] - i) ** 2 + (c[1] - j) ** 2)
b[i, j] = b[closest_key]
But it is very slow probably because there are 127*127 loops in which we loop again once over all elements to compute the distance!
How can we populate a dict with missing values, with nearest neighbour, in a more efficient way?