如何从Python中的列表创建嵌套字典?

时间:2016-11-03 12:46:27

标签: python list dictionary

我有一个字符串列表:tree_list = ['Parents', 'Children', 'GrandChildren']

我如何获取该列表并将其转换为这样的嵌套字典?

tree_dict = {
    'Parents': {
        'Children': {
            'GrandChildren' : {}
        }
    }
}

print tree_dict['Parents']['Children']['GrandChildren']

3 个答案:

答案 0 :(得分:14)

这种最简单的方法是从内到外构建字典:

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

答案 1 :(得分:7)

50 46 44字节

尝试打高尔夫球:

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)