Is it possible to turn a list into a nested key key * without * recursion?

Suppose I have a list:

mylist = ['a','b','c','d'] 

Is it possible to create the following dict from this list without using a recursion / recursive function?

 { 'a': { 'b': { 'c': { 'd': { } } } } } 
+7
source share
5 answers

For a simple case, just iterate and build, starting from the end or from the beginning:

 result = {} for name in reversed(mylist): result = {name: result} 

or

 result = current = {} for name in mylist: current[name] = {} current = current[name] 

The first solution can also be expressed as single-line using reduce() :

 reduce(lambda res, name: {name: res}, reversed(mylist), {}) 
+11
source

For this simple case, at least yes:

 my_list = ['a', 'b', 'c', 'd'] cursor = built_dict = {} for value in my_list: cursor[value] = {} cursor = cursor[value] 
+3
source

Or for imagination and reduced readability:

 dict = reduce(lambda x, y: {y: x}, reversed(myList), {}) 
+3
source

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': {}}}}} 
+1
source
 mydict = dict() currentDict = mydict for el in mylist: currentDict[el] = dict() currentDict = currentDict[el] 
0
source

All Articles