Climbing up in constant time

Sample tree tree = [(1,2), (2,3), (4,3), (3, 5), (6, 7), (8, 7), (7, 5)] d = {k: v for k, v in tree} # Go from 1 to 5 (3 levels) print(d[d[d[1]]]) # 5 # From 4 to 3 (1 level) print(d[4]) # 3 # From 8 to 5 (2 levels) print(d[d[8]]) # 5