我有一个未知层次深度的字典:
dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
我找到了the following useful来学习如何解决这个问题,但是我在修改代码以获取我想要的内容方面遇到了麻烦,这是一个包含所有路径的列表到死胡同的最高等级。
所需的输出是:
list = ['a,b,c', 'a,b,d', 'a,b,e', 'f,g']
为了开始接近这个,我使用了DFS方法:
hierarchy = []
for parent in dict_of_dicts:
recurse_dicts(concepts, parent, hierarchy)
def recurse_dicts(concepts, parent, hierarchy):
hierarchy.append(parent)
for child in concepts[parents]:
if len(recurse[node][child].keys()) > 0:
recurse_dicts(recurse[node], child, hierarchy)
else:
return
这导致:
hierarchy = ['a', 'b', 'c', 'd', 'e']
这是某种东西,但不是我想要的东西。
答案 0 :(得分:0)
假设您的值始终词典,您可以使用:
def paths(d, path=(), res=None):
if res is None:
res = []
for key, value in d.iteritems():
if not value:
# end of the line, produce path
res.append(','.join(path + (key,)))
else:
# recurse down to find the end of this path
paths(value, path + (key,), res)
return res
这使用共享列表(在第一次调用时生成)将生成的生成路径传递回调用者,并为每个递归步骤构建路径,以便在遇到空值时将其添加到结果列表中。
演示:
>>> dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
>>> paths(dict_of_dicts)
['a,b,c', 'a,b,e', 'a,b,d', 'f,g']
路径未排序,因为词典没有顺序;如果需要,你仍然可以对键进行排序:
for key in sorted(d):
value = d[key]
而不是for key, value in d.iteritems()
循环。
答案 1 :(得分:0)
这是一个递归DFS过程,用于跟踪每个分支的路径:
dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
def dfs(path, d):
if d == {}:
print path;
for item in d:
dfs(path+[item],d[item])
dfs([],dict_of_dicts)
输出:
['a', 'b', 'c']
['a', 'b', 'e']
['a', 'b', 'd']
['f', 'g']