解析字典中的嵌套列表

时间:2019-05-15 09:13:01

标签: python dictionary tree

我创建了类似于“家谱”的数据,并设法将其转换为python字典。格式为:{parent:[child1, child2, ..., childn]}。所以我当前的字典是这样的:

{
'harry': ['jane', 'cara'], 
'jane': ['joe'], 
'cara': ['diane'], 
'joe': [], 
'diane': ['george'], 
'george': []
}

我想做的是将父母“融合”在孩子身上。我很难解释,所以我只展示一下。

这就是我要发生的事情:

{
'harry': {
    'jane': {
        'joe': []
    }
    ,'cara': {
        'diane': {
            'george' : []
        }
    }
}
}

非常感谢您

1 个答案:

答案 0 :(得分:1)

您可以像下面这样递归来实现:

tree_dict = {
    'harry': ['jane', 'cara'], 
    'jane': ['joe'], 
    'cara': ['diane'], 
    'joe': [], 
    'diane': ['george'], 
    'george': []
}

def process_parent_tree(parent):
    result = {}
    children = tree_dict[parent]
    if children:
        for child in children:
            result[parent] = process_parent_tree(child)
    else:
        result[parent] = []
    return result

merged_dict = {}
for parent in tree_dict:
    merged_dict.update(process_parent_tree(parent))