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

How to scrape out all of the items in dictionary – Python

I’m working on a ‘bookmarks’ related app. I have a dictionary data that contains all of the bookmarks from the browser. The input looks like this:

data = {
    "bookmarks_tab": {
        'children': [
            # This parent folder contains multiple nested folders, eg:
            {
                'name': 'nested folder 1',
                'type': 'folder',
                'children': [
                    # Now this nested folder can have multiple nested folders!
                    {
                        'name': 'nested subfolder',
                        'type': 'folder',
                        'children': [
                            # So on and on
                        ]
                    }
                ]
            }

        ],
        'type': 'folder',
        'name': 'bookmarks_tab'
    }
}

What approach should I take to find out how many folders (including nested sub folders) does the input have, including its name. Remember it can literally have any amount of nested folders.

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

>Solution :

You want a list of the names of all folders including sub-folders? If so, the approach to this is recursively looping through all items, checking if they are a folder and if they are, append their name to a list. For example:

def find_folders(parent: dict) -> list:
    # List of names of all folders found
    folders = []

    for folder in parent:
        if folder['type'] == 'folder':
            folders.append(folder.get('name'))
            folders.extend(find_folders(folder.get('children', [])))

    return folders

print(find_folders(data['bookmarks_tab']['children']))
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