I have a dictionary that isn't behaving as I expect, what's wrong with it?

Example dictionary

{
"01_timelines": {
    "00_data-managment": {},
    "01_rush-and-spot": {}
},
"02_source": {
    "00_from_external": {
        "01_fonts": {},
        "02_logos": {},
        "03_graphics": {},
        "04_video": {},
        "05_3d": {}
    },
    "01_imported_projects": {}

}

I’ve looked at:
How to completely traverse a complex dictionary of unknown depth?

and some others but If I run the function on my dictionary it will return empty??
I don’t know why.

I’m trying to create a custom function:

def print_dict(myfolders,depth,breadcrumb,olddepth):
    
depth += 1
for key,value in myfolders.items():
          
    if isinstance(value, dict):
        if depth == 0:
            olddepth = depth
            breadcrumb = []
            # print(key)
            breadcrumb.append(key)
        elif depth != olddepth:
            olddepth = depth
            # tmp = breadcrumb
            # tmp.pop()
            # tmp.append(key)
            breadcrumb.append(key)
            print(breadcrumb,key)
        else:
            print(breadcrumb,key)
        
    print_dict(value,depth,breadcrumb,olddepth)

But it’s not completely working:
Output needs to be a list:

['01_timelines', '00_data-managment']
['01_timelines', '01_rush-and-spot']
['02_source', '00_from_external']
['02_source', '00_from_external','01_fonts']
['02_source', '00_from_external','02_logos']

enz

>Solution :

You can replace print_dict function with the following one and reduce passing arguments

myfolders = {
    "01_timelines": {
        "00_data-managment": {},
        "01_rush-and-spot": {}
    },
    "02_source": {
        "00_from_external": {
            "01_fonts": {},
            "02_logos": {},
            "03_graphics": {},
            "04_video": {},
            "05_3d": {}
        },
        "01_imported_projects": {}
    }
}

def print_dict(myfolders, breadcrumb=[]):
    for key, value in myfolders.items():
        breadcrumb_now = breadcrumb + [key]
        print(breadcrumb_now)

        if isinstance(value, dict):
            if value: # if value dictionary is not empty then go deep
                print_dict(myfolders[key], breadcrumb_now)
print_dict(myfolders)

This will result in following output

['01_timelines']
['01_timelines', '00_data-managment']
['01_timelines', '01_rush-and-spot']
['02_source']
['02_source', '00_from_external']
['02_source', '00_from_external', '01_fonts']
['02_source', '00_from_external', '02_logos']
['02_source', '00_from_external', '03_graphics']
['02_source', '00_from_external', '04_video']
['02_source', '00_from_external', '05_3d']
['02_source', '01_imported_projects']

Leave a Reply