I have the following python dictionary:
a = {'name': 'Kestral',
'children': [
{'name': 'Burtree Lane',
'children': [
{'name': 'ARCHIVE',
'children': []},
{'name': 'Development',
'children': [
{'name': 'Fee Proposals',
'children': []}]}]}]}
and i’m trying to write a recursive function to produce the following dictionary:
{'name': 'Kestral',
'folder': 'Kestral',
'children': [
{'name': 'Burtree Lane',
'folder': 'Kestral/Burtree Lane',
'children': [
{'name': 'ARCHIVE',
'folder': 'Kestral/Burtree Lane/ARCHIVE',
'children': []},
{'name': 'Development',
'folder': 'Kestral/Burtree Lane/Development',
'children': [
{'name': 'Fee Proposals',
'folder': 'Kestral/Burtree Lane/Development',
'children': []}]}]}]}
This is my python code:
def build_structured_dict(data, parent_path="/"):
new_dict = {
"name": data["name"],
"folder": f"{parent_path}{data['name']}" if parent_path else data["name"],
"children": [],
}
for child in data["children"]:
child_path = f"{parent_path}{data['name']}" if parent_path else ""
new_dict["children"].append(build_structured_dict(child, f"{child_path}/{child['name']}"))
return new_dict
But this returns:
{'name': 'Kestral',
'folder': '/Kestral',
'children': [{
'name': 'Burtree Lane',
'folder': '/Kestral/Burtree LaneBurtree Lane',
'children': [{
'name': 'ARCHIVE',
'folder': '/Kestral/Burtree LaneBurtree Lane/ARCHIVEARCHIVE',
'children': []},
{'name': 'Development',
'folder': '/Kestral/Burtree LaneBurtree Lane/DevelopmentDevelopment',
'children': [{
'name': 'Fee Proposals',
'folder': '/Kestral/Burtree LaneBurtree Lane/DevelopmentDevelopment/Fee ProposalsFee Proposals',
'children': []}]}]}]}
Can someone help me in removing these duplicates?
>Solution :
You’re concatenating the "name" attribute both as argument to the recursive call (child["name"]) as in that recursive execution itself data["name"], causing the duplication.
Here is a correction to your code, which keeps the initial slash which you also produced in your code:
def build_structured_dict(data, parent_path="/"):
path = f"{parent_path}{data['name']}"
new_dict = {
"name": data["name"],
"folder": path,
"children": [],
}
for child in data["children"]:
new_dict["children"].append(build_structured_dict(child, path + "/"))
return new_dict
If you don’t want the initial slash (as depicted in your desired output), then set the default value for the second parameter to the empty string.