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 dict
my_dict = {1.0:"apple", 2.0: "orange", 3.0:"banana", 4.0:"coconut"}
#get nearest dict instance
n_dict = NearestDict(my_dict)
#access element using nearest key
print(n_dict[1.3])

Code explanation

In the above code snippet:

  • Line 1: We import the NearestDict method from sortedcollections.
  • Line 4: We declare and initialize the unsorted dictionary my_dict.
  • Line 7: We get the NearestDict instance of my_dict and assign it to variable n_dict.
  • Line 10: We try to access the element which has key 1.0 using the key 1.3. It displays the value of banana even though the key 1.3 is not present in the dict, but it displays the result since the key 1.3 is nearest to the key 1.0.

Free Resources