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' [,...] } } }   
8
  • Have you tried writing a recursive function, like the one here? stackoverflow.com/questions/60230113/… Commented Dec 2, 2022 at 3:14
  • That looks like a way to recursively parse a JSON, I'm looking to build a JSON based on recursively checking subfolders. Thanks! Commented Dec 2, 2022 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()? Commented Dec 3, 2022 at 4: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! Commented Dec 4, 2022 at 5:04
  • 1
    Something roughly like def walk(dir): return {'folder': dir, 'children': [walk(c) for c in dir.child if isinstance(c, Folder)]} Commented Dec 4, 2022 at 5:36

1 Answer 1

1

Something roughly like

def walk(dir):
  return {
    'folder': dir,
    'children': [walk(c) for c in dir.child if isinstance(c, Folder)]
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.