Python dictionary - binary search for a key?

后端 未结 5 1328
长发绾君心
长发绾君心 2021-02-05 19:16

I want to write a container class that acts like a dictionary (actually derives from a dict), The keys for this structure will be dates.

When a key (i.e. date) is used t

5条回答
  •  猫巷女王i
    2021-02-05 19:52

    I'd extend a dict, and override the __getitem__ and __setitem__ method to store a sorted list of keys.

    from bisect import bisect
    
    class NearestNeighborDict(dict):
        def __init__(self):
            dict.__init__(self)
            self._keylist = []
    
        def __getitem__(self, x):
            if x in self:
                return dict.__getitem__(self, x)
    
            index = bisect(self._keylist, x)
            if index == len(self._keylist):
                raise KeyError('No next date')
    
            return dict.__getitem__(self, self._keylist[index])
    
        def __setitem__(self, x, value):
            if x not in self:
                index = bisect(self._keylist, x)
                self._keylist.insert(index, value)
    
            dict.__setitem__(self, x, value)
    

    It's true you're better off inheriting from MutableMapping, but the principle is the same, and the above code can be easily adapted.

提交回复
热议问题