I have a list of lines: tree_list = ['Parents', 'Children', 'GrandChildren']
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']
The easiest way is to create a dictionary, starting inside out:
tree_dict = {} for key in reversed(tree_list): tree_dict = {key: tree_dict}
Trying to play golf:
lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
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)
Source: https://habr.com/ru/post/1259220/More articles:Does javascript STOMP client work in browser / frontend js? - javaChoose values ββbetween two ranges of columns - sqlftruncate failed a second time - unixwindow.onbeforeunload does not start in Chrome, but works in Firefox - javascriptHow can I run a scheduled Kubernetes task manually? - scheduled-tasksIs it possible to overwrite str% behavior with __rmod__? - pythonIOS Opus Decoder Crashing for No Apparent Reason - iosAccess WCF service from a mobile client with user authentication - authenticationIs it possible to specify the name of params array parameters using the nameof operator? - c #OError: [Errno 26] The text file is busy: '/...myvirtualenv/bin/python' - pythonAll Articles