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

Create nested dictionary from directory

I have a folder with files named like this

Max_1.wav
Max_2.wav
Max_3.wav
Toto_1.wav
Toto_2.wav
Toto_3.wav
Valtteri_1.wav
Valtteri_2.wav
Valtteri_3.wav

I want to achieve this result

dict = {
    'Max': {
        'Max_1': {'path': 'database/Max_1.wav'},
        'Max_2': {'path': 'database/Max_2.wav'},
        'Max_3': {'path': 'database/Max_3.wav'}
    },

    'Toto': {
        'Toto_1': {'path': 'database/Toto_1.wav'},
        'Toto_2': {'path': 'database/Toto_2.wav'},
        'Toto_3': {'path': 'database/Toto_3.wav'}
    },

    'Valtteri': {
        'Valtteri_1': {'path': 'database/Valtteri_1.wav'},
        'Valtteri_2': {'path': 'database/Valtteri_2.wav'},
        'Valtteri_3': {'path': 'database/Valtteri_3.wav'}
    }

}

This is the code I’ve been working on and the result I’m getting

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

dict = {}

for x in os.listdir(directory):
    dict[x[:-6]] = {}

for x in os.listdir(directory):
    for key in dict:
        if x[:-6] == key:
            dict[key] = {x[:-4]: {'path': f'database/{x}'}}

Which gives me this. I think it’s because the keys are overwritten because of the for loop, but I can’t seem to wrap my head around a solution.

dict = {
    'Max': {
        'Max_3': {'path': 'database/Max_3.wav'}
    },

    'Toto': {
        'Toto_3': {'path': 'database/Toto_3.wav'}
    },

    'Valtteri': {
        'Valtteri_3': {'path': 'database/Valtteri_3.wav'}
    }

}

Help would be appreciated thank you

>Solution :

instead of using the assignment operator here:

dict[key] = {x[:-4]: {'path': f'database/{x}'}}

call the update method on the dictionary:

dict[key].update({x[:-4]:{'path': f'database/{x}'}})
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