+ 1

previous key and next value access in Dictionary

#Write a function called rabbit_hole. rabbit_hole should have two parameters: a #dictionary and a string. The string may be a key to the dictionary. The value associated #with that key, in turn, may be another key to the dictionary. Keep looking up the keys #until you reach a key that has no associated value. Then, return that key. #For example, imagine if you had the following dictionary. This one is sorted to make this example easier to follow: # d = {"bat": "pig", "pig": "cat", "cat": "dog", "dog": "ant", # "cow": "bee", "bee": "elk", "elk": "fly", "ewe": "cod", # "cod": "hen", "hog": "fox", "fox": "jay", "jay": "doe", # "rat": "ram", "ram": "rat"} #If we called rabbit_hole(d, "bat"), then our code should... # - Look up "bat", and find "pig" # - Look up "pig", and find "cat" # - Look up "cat", and find "dog" # - Look up "dog", and find "ant" # - Look up "ant", and find no associated value, and so it would # return "ant". #Notice that if the initial string passed in is not a key in the dictionary, that string should be returned as the result as well. #Note, however, that it is possible to get into a loop. In the dictionary above, rabbit_hole(d, "rat") would infinitely go around between "rat" and "ram". You should prevent this: if a key is ever accessed more than once (meaning a loop has been #reached), return the boolean False. #Hint: If you try to access a value from a dictionary that does #not exist, a KeyError will be raised. #Write your function here! def rabbit_hole(myDict, mystring): get_string = mystring try: for key, value in myDict.items(): if get_string in myDict.keys() : get_string = myDict[get_string] else: return get_string except KeyError: return False print(rabbit_hole(d, "rat")) print(rabbit_hole(d, "yak")) I am getting the right answer for 'yak' but not for 'rat' since it is looping. Can anyone help me fix it.

23rd Nov 2020, 1:23 PM
NG_
NG_ - avatar
4 ответов
+ 1
Good thing you leave the parameter mystring untouched. After setting get_string in the loop you can compare get_string to mystring and return or raise an error if equal
23rd Nov 2020, 1:33 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
You can delete the if statement and use the try except instead (return get_string instead of False)
23rd Nov 2020, 1:37 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
if part leading to wrong.. According to question, you shloud try get_string = myDict[get_string] if it raise error, then return values where it stopped otherwise return value at loop end..
23rd Nov 2020, 2:26 PM
Jayakrishna 🇮🇳
+ 1
Thank you Benjamin Jürgens and Jayakrishna🇮🇳 for your input. It works now.
23rd Nov 2020, 7:07 PM
NG_
NG_ - avatar