It is worth noting that each recursion can be transformed into an iteration , although sometimes it may not be so simple. For a specific example in the question, this is quite simple, it is simply a matter of accumulating the expected result in a variable and moving the input list in the appropriate order. Here is what I mean:
def convert(lst): acc = {} for e in reversed(lst): acc = {e: acc} return acc
Or even shorter, the aforementioned algorithm can be expressed as single-line (it is assumed that Python 2.x, in Python 3.x reduce was moved to the functools module). Note how the variable names in the previous solution correspond to the lambda parameters, and how in both cases the initial accumulator value {} :
def convert(lst): return reduce(lambda acc, e: {e: acc}, reversed(lst), {})
In any case, the convert function works as expected:
mylist = ['a','b','c','d'] convert(mylist) => {'a': {'b': {'c': {'d': {}}}}}
รscar Lรณpez
source share