I have an API I'm accessing, which has a deep folder structure. I don't know the depth of the folder structure(definitely more than 4 levels and each folder has a different depth) but I want to get all folder, subfolder names and put them in a dict. As each folder has a name and id and I only can access the folder with the id, but need to match the name to make it usable. I'm still far from being an experienced coder so I hope someone can help me with this. As I came across this issue multiple times with different APIs. How should I for-loop when I don't know how many levels of subfolders there are?
folder_ids = []
folder_names = []
folders_dict = {}
response_list = client.get_asset_children(assetid) # Get subfolder and files from asset with API
assets = response_list.results
for item in assets:
folder_ids.append(item['id'])
folder_names.append(item['name'])
folder_dict.update(dict(zip(folder_names, folder_ids)))
It is super slow "around 40seconds" but it's the first solution that worked. I hope you guys can help me to solve this puzzle with faster code. I used a recursive function.
def get_subassets(assetid): # Version 004
"""List Assets"""
response_list = client.get_asset_children(assetid)
assets = response_list.results
global assets_dict # Create a global variable for assets dictionary
assets_dict = {} # Create the empty assets dictionary
for item in assets:
if item['type'] == 'folder':
all_folders.append(item['name'])
get_subassets(item['id'])
# print("It's a folder: ", item['name'])
if item['type'] == 'file':
all_files.append(item['name'])
# print("It's a file: ", item['name']