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.

>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']))

Leave a Reply