小编典典

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

python

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

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

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

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

阅读 225

收藏
2021-01-20

共1个答案

小编典典

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

tree_dict = {}
for key in reversed(tree_list):
    tree_dict = {key: tree_dict}
2021-01-20