Parsing nested list in dictionary

I have created data similar to a "family tree" and managed to convert it into a python dictionary. The format is: {parent:[child1, child2, ..., childn]}. So my current dictionary is like this:

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

What I want to do is to "merge" the parents on their children. It's quite difficult for me to explain so I will just show this.

This is what I want to happen:

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

Thank you very much

Upvotes: 0

Views: 66

Answers (1)

Viktor Petrov
Viktor Petrov

Reputation: 444

You can achieve this with recursion like so:

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))

Upvotes: 1

Related Questions