我有一个字符串列表:tree_list = ['Parents', 'Children', 'GrandChildren']
我如何获取该列表并将其转换为这样的嵌套字典?
tree_dict = {
'Parents': {
'Children': {
'GrandChildren' : {}
}
}
}
print tree_dict['Parents']['Children']['GrandChildren']
答案 0 :(得分:14)
这种最简单的方法是从内到外构建字典:
tree_dict = {}
for key in reversed(tree_list):
tree_dict = {key: tree_dict}
答案 1 :(得分:7)
尝试打高尔夫球:
lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
答案 2 :(得分:5)
使用递归函数:
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)