It is to everyone, not just to the last. There is a solution, but I would like to see an elegant option.
Test dictionary:
test = {'a': {'b': {'c': {},'d': {'e': {}}}}} Due conclusion:
[('a',), ('a', 'b'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'b', 'd', 'e')] My decision:
First, find the path to the final key of each nested dictionary:
def recurse(inp_dict, path=()): if inp_dict: for key in inp_dict: for rv in recurse(inp_dict[key], path + (key,)): yield rv else: yield path after_recurse = recurse(test) list(after_recurse) [Out]: [('a', 'b', 'c'), ('a', 'b', 'd', 'e')] Next, we shorten each resulting tuple by one last element in the loop, add to the existing tuples, and uniquely list:
result = set([x[:y + 1] for x in after_recurse for y in range(len(x))]) sorted(result) [Out]: [('a',), ('a', 'b'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'b', 'd', 'e')]