how to jump from key to values in dictionary to create a list of cycles?

In my homework, a cycle is defined as a set of keys that jump from key -> value -> key that returns to its original starting value. For instance:
d1 = {1:6, 3:1, 6:3}
cycles = [[1, 6, 3]]

because 1:6 -> 6:3 -> 3:1, and the starting key == last value

Similarly for the following dictionary:

d1 = {1: 5, 2: 14, 3: 15, 4: 3, 5: 5, 6: 5, 7: 15, 8: 6, 9: 10, 10: 15, 11: 12, 12: 15, 13: 14, 14: 8, 15: 9}

Properly ordered, the cycles given by the mapping are: [[5], [9, 10, 15]]
(also because 5:5 is a complete cycle, and 9:10 -> 10:15 -> 15:9)

Is there a way to create a loop to track these cycles in dictionaries? I wish to create a line that would work for any random key-value dictionary mappings.

Any help would be much appreciated. 

Re: how to jump from key to values in dictionary to create a list of cycles

This is a common task in “graph algorithms”. You are looking for cycles in a graph, where a vertex of the graph is represented as an entry in your dictionary. If you google for “graph algorithm cycles” you can find more information.

1 Like