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

后端 未结 2 1403
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 03:47

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


        
2条回答
  •  太阳男子
    2021-01-14 04:08

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

提交回复
热议问题