简体   繁体   中英

Recursively going through a dictionary

So I have a dictionary;

dictionary = {"one": ["two"], "two": ["three"], "three": [None]}

How can I recursively go through in a function to find one if i am given three? example: does one end up as three? Yes because one --> two --> three and the same back down. three --> two --> one

So far I have tried to use a list comprehension on the dictionary;

def function(start, end, dict_to_check):
    if dict_to_check[end] == start:
        return True
    else:
        var = {key: value for key, value in dict_to_check.items() if value == start}
        return var

but this does not use recursion and I have no idea how to go about

You can try this:

start = "one"
end = "three"
dictionary = {"one": ["two"], "two": ["three"], "three": [None]}
def check(s):
  if not dictionary[s][0]:
     return "Not found"
  if dictionary[s][0] == end:
     return "found"
  else:
     return check(dictionary[s][0])


print(check(start))

Output:

found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM