What is the NearestDict method in Python?
Overview
In Python, a dictionary is an unsorted key-value pair data structure, where key-value pairs are comma-separated. It is useful for efficient lookups.
If we want to get any value for a key, we need to provide the exact key value, but by using the NearestDict method we can get the value of the key if the requested key is near to it.
For example, if we have keys in the dict as 1.0 , 2.0 , 3.0 and if the requested key is 1.3 , then we get the value for the 1.0 key, as the 1.3 key is nearer to the key 1.0.
Syntax
We need to get the NearestDict instance from a normal dict:
NearestDict(my_dict)
Code example
Let's look at the code below:
from sortedcollections import NearestDict#normal dictmy_dict = {1.0:"apple", 2.0: "orange", 3.0:"banana", 4.0:"coconut"}#get nearest dict instancen_dict = NearestDict(my_dict)#access element using nearest keyprint(n_dict[1.3])
Code explanation
In the above code snippet:
- Line 1: We import the
NearestDictmethod fromsortedcollections. - Line 4: We declare and initialize the unsorted dictionary
my_dict. - Line 7: We get the
NearestDictinstance ofmy_dictand assign it to variablen_dict. - Line 10: We try to access the element which has key
1.0using the key1.3. It displays the value ofbananaeven though the key1.3is not present in thedict, but it displays the result since the key1.3is nearest to the key1.0.