Given the following list:
a = [
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c1', 'child_name': 'cn1'},
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c2', 'child_name': 'cn2'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c3', 'child_name': 'cn3'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c4', 'child_name': 'cn4'},
{'parent': 'c4', 'parent_name': 'cn4', 'child': 'c5', 'child_name': 'cn5'},
{'parent': 'c2', 'parent_name': 'cn2', 'child': 'c6', 'child_name': 'cn6'},
{'parent': 'c3', 'parent_name': 'cn3', 'child': 'c7', 'child_name': 'cn7'}
]
I want to create a hierarchical dict of lists So far I've made this code which runs fine, but for some reason the children c3 and c4 are repeated twice. Where did I made a mistake?
def build(key):
children = [(item['child'], item['child_name']) for item in a if item['parent'] == key]
data = {}
for k, name in children:
data[k] = {'child': k, 'child_name': name, 'children': []}
for item in a:
if item['parent'] == k:
data[k]['children'].append(build(k))
return data
EDIT: The code above produce this output:
{'c1': {'child': 'c1',
'child_name': 'cn1',
'children': [{'c3': {'child': 'c3',
'child_name': 'cn3',
'children': [{'c7': {'child': 'c7',
'child_name': 'cn7',
'children': []}}]},
'c4': {'child': 'c4',
'child_name': 'cn4',
'children': [{'c5': {'child': 'c5',
'child_name': 'cn5',
'children': []}}]}},
{'c3': {'child': 'c3',
'child_name': 'cn3',
'children': [{'c7': {'child': 'c7',
'child_name': 'cn7',
'children': []}}]},
'c4': {'child': 'c4',
'child_name': 'cn4',
'children': [{'c5': {'child': 'c5',
'child_name': 'cn5',
'children': []}}]}}]},
'c2': {'child': 'c2',
'child_name': 'cn2',
'children': [{'c6': {'child': 'c6',
'child_name': 'cn6',
'children': []}}]}}
I would need the exact same output but obviously without the duplications (here the children of c1 are repeated twice)