Skip to content Skip to sidebar Skip to footer

Find A Key In A Python Dictionary And Return Its Parents

I have a nested dictionary that has a list of folders, like this one where 2013_09_10 is the root folder: {'2013_09_10': {'master.tex': None, 'master.log': None, 'master.pdf': None

Solution 1:

Save the path of the preceding directories in a second argument, prefix:

import os
def get_files(directory, prefix=[]):
    for filename in directory.keys():
        path = prefix+[filename]
        if not isinstance(directory[filename], dict):
            print os.path.join(*path)
        else:
            get_files(directory[filename], path)

Post a Comment for "Find A Key In A Python Dictionary And Return Its Parents"