Custom dictionary lookup in Python

前端 未结 3 1024
时光说笑
时光说笑 2021-02-05 18:04

if I have a dictionary like this

>>> d = {10: 3, 100: 2, 1000: 1}

I can type something like:

>>> d.get(10), d         


        
3条回答
  •  被撕碎了的回忆
    2021-02-05 18:39

    You can derive from dict to change the behaviour of the get() method:

    class ClosestDict(dict):
        def get(self, key):
            key = min(self.iterkeys(), key=lambda x: abs(x - key))
            return dict.get(self, key)
    
    d = ClosestDict({10: 3, 100: 2, 1000: 1})
    print (d.get(20), d.get(60), d.get(200))
    

    prints

    (3, 2, 2)
    

    Note that the complexity of get() no longer is O(1), but O(n).

提交回复
热议问题