You are looking for a recursive function that builds a dictionary with the first list element as a key and the transformed rest of the list as the value:
l = [1, 2, 3, 4, 5]
def l2d(l):
if len(l) < 2: # Not good
raise Exception("The list is too short")
if len(l) == 2: # Base case
return {l[0]: l[1]}
# Recursive case
return {l[0]: l2d(l[1:])}
l2d(l)
# {1: {2: {3: {4: 5}}}}
Another interesting approach is to use functools.reduce
:
from functools import reduce
reduce(lambda tail,head: {head: tail}, reversed(l))
# {1: {2: {3: {4: 5}}}}
It progressively applies a dictionary construction function to the first element of the list and the rest of it. The list is reversed first, so the construction naturally starts at the end. If the list is too short, the function returns its first element, which may or may not be desirable.
The "reduce" solution is MUCH FASTER, by about two orders of magnitude. The bottom line: avoid recursion.