Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to turn a list into a nested dict of keys *without* recursion?

Supposing I had a list as follows:

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

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

{
  'a': {
    'b': {
      'c': {
        'd': { }
      }
    }
  }
}
like image 463
Phillip B Oldham Avatar asked Nov 05 '12 18:11

Phillip B Oldham


3 Answers

For the simple case, simply iterate and build, either from the end or the start:

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 a one-liner using reduce():

reduce(lambda res, name: {name: res}, reversed(mylist), {})
like image 60
Martijn Pieters Avatar answered Sep 28 '22 08:09

Martijn Pieters


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]
like image 43
Silas Ray Avatar answered Sep 28 '22 07:09

Silas Ray


Or for fancyness and reduced readability:

dict = reduce(lambda x, y: {y: x}, reversed(myList), {})
like image 22
Jesse the Game Avatar answered Sep 28 '22 07:09

Jesse the Game