16

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
  • 35,097
  • 12
  • 75
  • 106
JokerMartini
  • 5,219
  • 4
  • 55
  • 162

3 Answers3

33

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
  • 530,615
  • 113
  • 910
  • 808
11

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,005
  • 2
  • 20
  • 41
10

This is a short solution:

lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
mkrieger1
  • 14,486
  • 4
  • 43
  • 54
Kh40tiK
  • 2,176
  • 18
  • 28