Search code examples
pythonpython-3.xdictionarytreeview

Python: create a nested dictionary from a list of parent child values


Here is the input:

list_child_parent= [
    #first value is child, second is parent
    (0, 1),
    (1, 3),
    (8, 7),
    (3, 6),
    (4, 3),
    (5, 3)
]

The output needs to create a nested dictionary tree using these values. The tree will never be more than 6 levels deep.

For example:

output_dict = {
    6: {3: {1: {0: {}}, 4: {}, 5: {}}}, 7: {8: {}}
}

I have spent two days trying to accomplish this. I have tried writing functions to find where the key is in the tree and then add the new key after it, but I cannot produce code that can continue more than 3 levels. It's baffling and I feel that there is probably a standard library that can do this.

My experience level is low.


Solution

  • Not pretty and probably not Pythonic, but it should get you going:

    #!/usr/bin/env python3
    
    def make_map(list_child_parent):
        has_parent = set()
        all_items = {}
        for child, parent in list_child_parent:
            if parent not in all_items:
                all_items[parent] = {}
            if child not in all_items:
                all_items[child] = {}
            all_items[parent][child] = all_items[child]
            has_parent.add(child)
    
        result = {}
        for key, value in all_items.items():
            if key not in has_parent:
                result[key] = value
        return result
    
    if __name__ == '__main__':
        list_child_parent = [
            #first value is child, second is parent
            (0, 1),
            (1, 3),
            (8, 7),
            (3, 6),
            (4, 3),
            (5, 3)
        ]
    
        actual = make_map(list_child_parent)
    
        expected = {
            6: {
                3: {
                    1: {
                        0: {}
                    },
                    4: {},
                    5: {}
                }
            },
            7: {
                8: {}
            }
        }
        print('OK' if expected == actual else 'FAIL')