Find a key in a python dictionary and return its parents -


i have nested dictionary has list of folders, 1 2013_09_10 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 , metaphors.txt': none, 'p2.tex': none}, 'master.aux': none, 'front_matter.tex': none}} 

what i' trying accomplish is, given name of file (for example p1.tex), print actual path of file

2013_09_10/pieces/p1.tex 

i've created piece of code gives me names of files, not parent keys (directiory):

def get_files(directory):     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 , metaphors.txt p2.tex master.aux front_matter.tex 

i think code need simple modification accomplish want, can't sort out.

save path of preceding directories in second argument, prefix:

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

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -