Closest implies that you define a distance function. For a point in space, the norm 2 is usually used. Let's code first a function that computes that norm between two points, but as we will probably have to use it against an iterator (or maybe because I foresee something, as a key function) we make it a closure (to find the closest value, that cool).
from math import sqrt
def norm2(ptA):
def norm2_close(ptB):
xA, yA, zA = ptA
xB, yB, zb = ptB
return sqrt((xA-xB)**2 + (yA-yB)**2 + (zA-zB)**2)
return norm2_close
Now, we can do
>>> normFromA = norm2([1, 2, 3])
>>> normFromA([3, 2, 1])
2.8284271247461903
>>> normfromA([4, 5, 6])
5.196152422706632
Very well. But we still need to get the minimum from your list of dicts. There are many possibilities, but as we wrote a nice closure, let's just modify it to suit our needs:
def norm2InDict(ptA):
def norm2InDict_close(dict_for_ptB):
xA, yA, zA = ptA
xB, yB, zB = dict_for_ptB['co-ordinate']
return sqrt((xA-xB)**2 + (yA-yB)**2 + (zA-zB)**2)
return norm2InDict_close
and let python do the boring work
>>> min(points, key=norm2InDict([1, 2, 3]))
{'co-ordinate': [0, 1, 3], 'Point': 2}
To understand the function, python will loop through the elements of the lists (each dictionary), apply the key function on them (that will compute the norm 2), compare the keys and return the element that has the smallest key. Right. And if I want the three closest elements, and not a single one? Well, the documentation tells us we can use the heapq module for that (I add some points to the list, for more fun):
>>> import heapq
>>> points=[
{'Point':1,'co-ordinate':[0,1,2]},
{'Point':2,'co-ordinate':[0,1,3]},
{'Point':3,'co-ordinate':[1,1,2]},
{'Point':4,'co-ordinate':[2,5,2]},
{'Point':5,'co-ordinate':[1,0,2]},
{'Point':6,'co-ordinate':[1,2,2]}
]
>>> heapq.nsmallest(3, points, key=norm2InDict([1, 2, 3]))
[{'co-ordinate': [1, 2, 2], 'Point': 6}, {'co-ordinate': [0, 1, 3], 'Point': 2}, {'co-ordinate': [1, 1, 2], 'Point': 3}]