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