def cycle(lst, val, stop=None):
    d = dict(lst)
stop = stop if stop is not None else val
while True:
    yield val
val = d.get(val, stop)
if val == stop:
    break
How to join links in Python to get a cycle?