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

问题描述 投票:0回答:3

我有一个字符串列表:

tree_list = ['Parents', 'Children', 'GrandChildren']

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

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

print tree_dict['Parents']['Children']['GrandChildren']
python list dictionary
3个回答
42
投票

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

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

具有任意终值:

result = ... # terminal value 
for k in reversed(keys):
    result = {k:  result}
# result is the nested dict

13
投票

使用递归函数:

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)

10
投票

这是一个简短的解决方案:

lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
© www.soinside.com 2019 - 2024. All rights reserved.