Find a key in a python dictionary and return its p

2019-08-10 02:39发布

问题:

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, 'Makefile': None, 'pieces': {'rastin.tex': None, '02 Human Information Processing.txt': None, 'p1.tex': None, 'p3.tex': None, '03 Models and Metaphors.txt': None, 'p2.tex': None}, 'master.aux': None, 'front_matter.tex': None}}

What I' trying to accomplish is, given the name of a file (for example p1.tex), print the actual path of the file

2013_09_10/pieces/p1.tex

I've created this piece of code but it only gives me the names of all files, not its parent keys (directiory):

def get_files(directory):
    for filename in directory.keys():
        if not isinstance(directory[filename], dict):
            print filename
        else:
            get_files(directory[filename])

Output:

master.tex
master.log
master.pdf
Makefile
rastin.tex
02 Human Information Processing.txt
p1.tex
p3.tex
03 Models and Metaphors.txt
p2.tex
master.aux
front_matter.tex

I think that my code just need a simple modification to accomplish what I want, but I can't sort this out.

回答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)