[英]How to create a nested dictionary from a list in Python?
我有一個字符串列表: tree_list = ['Parents', 'Children', 'GrandChildren']
我如何獲取該列表並將其轉換為這樣的嵌套字典?
tree_dict = {
'Parents': {
'Children': {
'GrandChildren' : {}
}
}
}
print tree_dict['Parents']['Children']['GrandChildren']
這種最簡單的方法是從內而外構建字典:
tree_dict = {}
for key in reversed(tree_list):
tree_dict = {key: tree_dict}
這是一個簡短的解決方案:
lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
使用遞歸函數:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.