0

I'm looking to build a dictionary based on a directory's subfolders. Note that this isn't an OS directory, so I can't use the os library. The below code works, but is limited to 3 levels of subdirectories. How can I build a loop that will handle any number of subdirectories?

 if isinstance(parentfolder, Folder):
    for child in parentfolder.child:
        subchildren = []
        if isinstance(child, Folder):
           for subchild in child.child: 
              if isinstance(subchild, Folder):
                 subchildren.append({'folder' : subchild})
           children.append({'folder' : subchildren})
    DirDict.append({'folder' : parentfolder, 'children': children })

The desired outcome is a dictionary that looks something like the following, while the child folder meets the "isinstance" condition :

{'folder' : 'somefolder', 'children' : { 'folder' : 'somechildfolder', 'children' : { 'folder' : 'somegrandchildfolder' [,...] } } }   
user2953714
  • 21
  • 1
  • 7
  • Have you tried writing a recursive function, like the one here? https://stackoverflow.com/questions/60230113/how-to-recursively-explore-python-nested-dictionaries – Nick ODell Dec 02 '22 at 03:14
  • That looks like a way to recursively parse a JSON, I'm looking to build a JSON based on recursively checking subfolders. Thanks! – user2953714 Dec 02 '22 at 13:20
  • An example input structure and expected output would be nice. What JSON are you trying to build? Why not use `json.dumps()`? – ggorlen Dec 03 '22 at 04:57
  • I've edited the question. It isn't the JSON piece that I'm struggling with, it's the loop to build the dictionary. How could I build a loop to append children/grandchildren/etc to a dictionary, without knowing the number of folders that have other folders inside of them? I'm looking to use a while loop instead of the 3 nested if statements I'm using in the code. I hope that helps explain my struggle. Thanks! – user2953714 Dec 04 '22 at 05:04
  • Edited to add an example outcome. – user2953714 Dec 04 '22 at 05:21
  • Although the example may be doing the reverse, using a recursive function might be the ticket, at least it'll be easy to write. Is there some reason you haven't looked at recursion? Note that any recursive implementation be made non-recursive as well - it's often a good place to get started and refactor from. – Grismar Dec 04 '22 at 05:29
  • 1
    Something roughly like `def walk(dir): return {'folder': dir, 'children': [walk(c) for c in dir.child if isinstance(c, Folder)]}` – Gene Dec 04 '22 at 05:36
  • Fantastic, that did it. If you could post it as an answer, I'll accept it. This was breaking my brain, so much appreciated! – user2953714 Dec 04 '22 at 15:36

1 Answers1

1

Something roughly like

def walk(dir):
  return {
    'folder': dir,
    'children': [walk(c) for c in dir.child if isinstance(c, Folder)]
  }
Gene
  • 46,253
  • 4
  • 58
  • 96