我有一本这样的字典:
dirDict = {"DIR1" : {
"DIR11" : {
"DIR111" : "Maki111",
"DIR112" : "Maki112"
},
"DIR12" : "Maki12",
"DIR13" : {
"DIR131" : "Maki131"
}
}
}
把它想象成一个文件夹结构。我想得到类似于os.walk
的文件夹结构。像这样:
["DIR1/DIR11/DIR111/Maki111",
"DIR1/DIR11/DIR112/Maki112",
"DIR1/DIR12/Maki12",
"DIR1/DIR13/DIR131/Maki131"]
所以它基本上是字典值的所有路径。我用递归函数尝试过很多种方法,但都迷路了。你知道吗
这是我的最新试验:
def walk(input_dict, path_string = "", result = ""):
for key, value in input_dict.items():
if isinstance(value, dict):
path_string += "/" + key
print "==== DICT ====", "\nkey: ", key, "\nvalue: ", value, "\n\t\tpath_string: ", path_string
result = walk(value, path_string)
print "\t\t\t\tresulting: ", result
elif isinstance(value, str):
print "==== NOT DICT ===="
path_string += "/" + value
print "\t\tpath_string: ", path_string, "\nvalue: ", value
return path_string
else:
path_string = "/" + key
result += "\n" + result
return result
使用Python 3:
输出:
我在https://gist.github.com/nvie/f304caf3b4f1ca4c3884#gistcomment-1597937发布的
walk
函数可以用作解决问题的助手:您的问题可以通过以下方式解决:
相关问题 更多 >
编程相关推荐