Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursively build a path from a python dictionary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading