Python Nearest dictionary coordinates

I have the following dictionary:

points = {'Location1': (76, 81), 'Location2': (75, 105), 'Location3': (76, 130), 'Location4': (76, 152)}

I try if I have a set of coordinates; coord = (x, y) to find the key with the closest pairs of values ​​in the coordinates. But I want to get a key that matches the closest.

I did it this way, but there should be a more efficient way.

points = {'Location1': (76, 81), 'Location2': (75, 105), 'Location3': (76, 130), 'Location4': (76, 152)}
array =  [(76, 81),  (75, 105),  (76,  130), (76,  152)]

def find_nearest(array,coord):

    dist = lambda s, d: (s[0] - d[0]) ** 2 + (s[1] - d[1]) ** 2

    result = min(array, key=partial(dist, coord))

    return result

found = find_nearest(array,coord)

print (list(points.keys())[list(points.values()).index(found)])
+4
source share
1 answer

You don't need to use list ( array) at all, you can pass dictionary ( points) to min; the dictionary key will be passed to the function key:

>>> from functools import partial
>>>
>>> def find_nearest(points, coord):
...     dist = lambda s, key: (s[0] - points[key][0]) ** 2 + \
...                           (s[1] - points[key][1]) ** 2
...     return min(points, key=partial(dist, coord))
...
>>> points = {'Location1': (76, 81), 'Location2': (75, 105),
...           'Location3': (76, 130), 'Location4': (76, 152)}
>>> find_nearest(points, (0, 0))
'Location1'
>>> find_nearest(points, (100, 100))
'Location2'
>>> find_nearest(points, (100, 200))
'Location4'

By accessing coordlambda directly, you can remove partial:

def find_nearest(points, coord):
    dist = lambda key: (coord[0] - points[key][0]) ** 2 + \
                       (coord[1] - points[key][1]) ** 2
    return min(points, key=dist)

or

def find_nearest(points, coord):
    x, y = coord
    dist = lambda key: (x - points[key][0]) ** 2 + (y - points[key][1]) ** 2
    return min(points, key=dist)
+1
source

Source: https://habr.com/ru/post/1673218/


All Articles