如何返回字典中满足条件的最后一个值

时间:2019-03-26 13:50:26

标签: python dictionary

代码应继续查找键,直到找到没有键为止 相应的值。只有这样才能返回该密钥。如果在跟踪过程中找不到密钥或找不到密钥,则必须返回最后一个密钥。

我已经使用递归跟踪到了最终的键/值对,但是我无法返回最终的跟踪值。

def rabbit_hole(d, word):    
    for key,val in d.items():    
        if key == word:    
            return rabbit_hole(d,val)

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"}

print(rabbit_hole(d, "bat"))

预期结果:蚂蚁
实际结果:无(因为在这种情况下,我无法返回最后一个值“ ant”)

2 个答案:

答案 0 :(得分:0)

递归函数(已完成)中的一个重要概念是基本情况。基本情况是停止递归并关闭备份堆栈的基础。在您的函数中,如果未找到键,则该函数不会返回任何值,这在python中意味着它的值为None

您应该做的是在循环外部以return word结尾该函数,这样,如果该函数没有在循环内部返回,您只需返回找到的最后一个单词。

此外,与问题无关,但请注意。您通过遍历项目来破坏字典的目的。相反,您应该做的是检查您要查找的单词是否在字典中,然后使用键访问器或使用.get()例如:

if word in d:
   val = d[word]

val = d.get(word)
if val is not None:
    return val

答案 1 :(得分:0)

我认为这就是您要寻找的-

dum = []    

def rabbit_hole(dic, word):    
    dum.append(word)

    if len(dum)>len(dic):
        print("Hey! this input is not right, there's no end to it..")
        return

    for key,val in dic.items():    
        if key == word:    
            return rabbit_hole(dic, val)
    return word

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": "mouse"}

print(rabbit_hole(d,"bat"))