Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a nested dictionary from a list in Python?

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']
like image 512
JokerMartini Avatar asked Nov 03 '16 12:11

JokerMartini


3 Answers

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}
like image 129
Sven Marnach Avatar answered Sep 28 '22 00:09

Sven Marnach


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)
like image 35
Guillaume Avatar answered Sep 28 '22 00:09

Guillaume


This is a short solution:

lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
like image 42
Kh40tiK Avatar answered Sep 27 '22 22:09

Kh40tiK