Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is the NearestDict method in Python?

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring