Python coding #3

InterviewQuery 37. Closest Key

Posted by Minyoung Jeong on September 13, 2020
Given a dictionary with keys of letters and values of a list of letters, find the key with the input value closest to the beginning of the list.

Example:

dictionary = {
    'a' : ['b','c','e'],
    'm' : ['c','e'],
}
input = 'c'

closest_key(dictionary, input) -> 'm'
 

c is at distance 1 from a and 0 from m. Hence closest key for c is m.

  

My solution:

  mydict = {
    'a' : ['b','c','e'],
    'm' : ['c','e'],
}

search='c'

mylist=[]

## iterate over dictionary values and store the index of the search word in the value list ##
for x in mydict.values():
    mylist.append(x.index(search))

## Get the closest position by using 'min'##
pos=mylist.index(min(mylist))

## Back out the key corresponding to the closest position index ##
print(list(mydict.keys())[pos])