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
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.
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.
__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.
A dictionary is 6.6 times faster than a list when we lookup in 100 items.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With