class NearestDict(dict):

    def __init__(self, ndims):
        super(NearestDict, self).__init__()
self.ndims = ndims

def __setitem__(self, key, val):
    if not isinstance(key, tuple):
        key = key,
if len(key) != self.ndims:
    raise KeyError('key must be %d dimensions' % self.ndims)
super(NearestDict, self).__setitem__(key, val)

@staticmethod
def __dist(ka, kb):
    assert len(ka) == len(kb)
return sum((ea - eb) ** 2 for ea, eb in zip(ka, kb))

def nearest_key(self, key):
    if not isinstance(key, tuple):
        key = key,
nk = min((k for k in self), key=lambda k: NearestDict.__dist(key, k))
return nk

def __missing__(self, key):
    if not isinstance(key, tuple):
        key = key,
if len(key) != self.ndims:
    raise KeyError('key must be %d dimensions' % self.ndims)
return self[self.nearest_key(key)]
Find integer nearest-neighbour in a dict