在字典中查找键直到没有更多关联值的函数 [英] function that looks up keys in a dictionary until there is no more associated values
问题描述
我需要帮助创建一个通过给定字典的函数.与该键关联的值可能是字典的另一个键.我需要这个函数来继续查找键,直到它找到一个没有关联值的键.
I need help creating a function that goes through a given dictionary. The value associated with that key may be another key to the dictionary. i need the function to keep looking up the keys until it reaches a key that has no associated value.
def follow_me(d, s):
while d:
if s in d:
return d[s]
我可以返回字典中 s 等于的值,但我不知道如何遍历它,直到得到一个没有关联值的值.所以我可以得到badger是doe的值,但是我如何遍历字典直到我得到fox然后fox to hen等.
I can return the value in the dictionary that s equals to but I've no idea how to iterate through it until I get a value that has no associated value. So I can get the value that badger is doe, but how do I iterate through the dictionary until I get fox and then fox to hen etc.
d = {'badger':'doe', 'doe':'fox', 'fox':'hen','hen':'flea',
'sparrow':'spider', 'zebra':'lion', 'lion':'zebra'}
print(follow_me(d, 'badger'))
print(follow_me(d, 'fox'))
print(follow_me(d, 'sparrow'))
print(follow_me(d, 'zebra'))
print(follow_me(d, 'aardvark'))
这就是我目前拥有的对我有意义的功能,因为我尝试过的其他一切都是错误的.
and this is what I currently have of the function that makes sense to me because everything else I've tried is just wrong.
def follow_me(d, s):
while d:
if s in d:
return d[s]
并且输出需要是:
flea
flea
spider
aardvark
但我现在的代码正在生成:
but my code right now is producing:
doe
hen
spider
lion
推荐答案
考虑到无限循环的存在,必须对此进行处理.您的描述不清楚在这种情况下会发生什么.
Considering the existence of infinite loops this has to be handled. Your description isn't clear about what should happen in this case.
def follow_me(d, key):
visited_keys = []
while key not in visited_keys and d[key]:
visited_keys.append(key)
key = d[key]
if not d[key]:
return key
return "this hunt has no end"
这篇关于在字典中查找键直到没有更多关联值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!