20

I have a list of strings: tree_list = ['Parents', 'Children', 'GrandChildren']

How can i take that list and convert it to a nested dictionary like this?

tree_dict = {
    'Parents': {
        'Children': {
            'GrandChildren' : {}
        }
    }
}

print tree_dict['Parents']['Children']['GrandChildren']
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

3 Answers3

42

This easiest way is to build the dictionary starting from the inside out:

tree_dict = {}
for key in reversed(tree_list):
    tree_dict = {key: tree_dict}
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Probably worth pointing out that if the leave has to be some other value than a `dict`, one can just initialise `tree_dict` accordingly. For example, `tree_dict = 42` leads to a nested dict where the innermost value is `42`. – MisterMiyagi Jun 10 '22 at 18:55
12

Using a recursive function:

tree_list = ['Parents', 'Children', 'GrandChildren']

def build_tree(tree_list):
    if tree_list:
        return {tree_list[0]: build_tree(tree_list[1:])}
    return {}

build_tree(tree_list)
Guillaume
  • 5,497
  • 3
  • 24
  • 42
10

This is a short solution:

lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Kh40tiK
  • 2,276
  • 19
  • 29