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

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

How can I take this list and convert it into a dictionary embedded in it?

 tree_dict = { 'Parents': { 'Children': { 'GrandChildren' : {} } } } print tree_dict['Parents']['Children']['GrandChildren'] 
+5
source share
3 answers

The easiest way is to create a dictionary, starting inside out:

 tree_dict = {} for key in reversed(tree_list): tree_dict = {key: tree_dict} 
+10
source

50 46 44 bytes

Trying to play golf:

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

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) 
+4
source

Source: https://habr.com/ru/post/1259220/


All Articles