21

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']

3 Answers 3

43

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}

With an arbitrary terminal value:

result = ... # terminal value 
for k in reversed(keys):
    result = {k:  result}
# result is the nested dict
Sign up to request clarification or add additional context in comments.

1 Comment

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.
13

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)

Comments

10

This is a short solution:

lambda l:reduce(lambda x,y:{y:x},l[::-1],{})

3 Comments

@Chris_Rands ah I totally agree with you. But readability is just one criterion.
You can save two characters by passing {} as the third argument to reduce() instead of prepending it to the list.
@Sven Marnach Good one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.