Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom dictionary lookup in Python

if I have a dictionary like this

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

I can type something like:

>>> d.get(10), d.get(100), d.get(1000)
(3, 2, 1)

Though I want that if the given key is not found, the value corresponding to the nearest key respect the given key is returned:

>>> d.get(20), d.get(60), d.get(200)
(3, 2, 2)

Instead the result in Python is

(None, None, None)

What's a Pythonic way to implement the behavior I described?

Thanks

like image 821
Paolo Avatar asked Apr 27 '11 18:04

Paolo


People also ask

What is lookup in dictionary in Python?

It will find and return the first dictionary that contains the given key, and can be easily modified to return a list of dictionaries if the keys are not unique.

What is a dictionary lookup?

This extension that allows you to quickly look up definitions of words and phrases in a clean inline box. The definitions come from Wiktionary, but have been preprocessed to reduce formatting and provide faster lookup.

What is self __ dict __ Python?

__dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.

How fast is Python dictionary lookup?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.


1 Answers

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).

like image 124
Sven Marnach Avatar answered Oct 02 '22 18:10

Sven Marnach