Find a key in a python dictionary and return its parents

佐手、 提交于 2019-12-11 09:38:29

问题


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)


来源:https://stackoverflow.com/questions/19214099/find-a-key-in-a-python-dictionary-and-return-its-parents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!