Python | Find the closest Key in dictionary
Last Updated :
14 Mar, 2023
The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + keys() + lambda The combination of above functions can be used to perform the particular task of finding the closest key in the dictionary. The keys function can be used to access the keys from the dictionary, lambda function can be used to formulate the logic and list comprehension to apply that all to whole list.
Python3
test_dict = { 13 : 'Hi' , 15 : 'Hello' , 16 : 'Gfg' }
search_key = 15.6
print ("The original dictionary is : " + str (test_dict))
res = test_dict.get(search_key) or test_dict[
min (test_dict.keys(), key = lambda key: abs (key - search_key))]
print ("The value to the closest key : " + str (res))
|
Time Complexity: O(n)
Space Complexity: O(1)
Output :
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The value to the closest key : Gfg
Method #2 : Using bisect_left() + OrderedDict() This method generally uses the binary search method of finding the nearest number. While being fast, it changes the ordering and also returns 2 potential candidates for nearest values, current and the next key’s value in sequence. And just returns position of key.
Python3
import collections
import bisect
test_dict = collections.OrderedDict()
test_dict = { 13 : 'Hi' , 15 : 'Hello' , 16 : 'Gfg' }
search_key = 15.6
print ("The original dictionary is : " + str (test_dict))
res = bisect.bisect_left( list (test_dict.keys()), 15.6 )
print ("The position of closest key : " + str (res))
|
Time Complexity: O(log n)
Space Complexity: O(n)
Output :
The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}
The position of closest key : 3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...