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)
CodePudding user response:
c3
, for example, is repeated twice because of line 2 below:
data[k] = {'child': k, 'child_name': name, 'children': []}
for item in a: # 'c3' will be found twice in a
if item['parent'] == k:
Because c3
occurs twice in a
, you add its children twice.
I'm not sure why you need to do that loop. To me it looks like it'll work if you remove that loop and just do data[k]['children'].append(build(k))
below data[k] = {'child': k, 'child_name': name, 'children': []}
:
data[k] = {'child': k, 'child_name': name, 'children': []}
data[k]['children'].append(build(k))