如何在Python中从列表创建嵌套字典? [英] How to create a nested dictionary from a list in Python?
本文介绍了如何在Python中从列表创建嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串列表: tree_list = ['Parents','Children','GrandChildren']
I have a list of strings: tree_list = ['Parents', 'Children', 'GrandChildren']
如何获取该列表并将其转换为这样的嵌套字典?
How can i take that list and convert it to a nested dictionary like this?
tree_dict = {
'Parents': {
'Children': {
'GrandChildren' : {}
}
}
}
print tree_dict['Parents']['Children']['GrandChildren']
推荐答案
最简单的方法是从内而外地构建字典:
This easiest way is to build the dictionary starting from the inside out:
tree_dict = {}
for key in reversed(tree_list):
tree_dict = {key: tree_dict}
这篇关于如何在Python中从列表创建嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文