Python 通过字典中的字典递归,始终从顶部开始
我有一本字典,内容如下,层次结构未知:Python 通过字典中的字典递归,始终从顶部开始,python,recursion,dictionary,Python,Recursion,Dictionary,我有一本字典,内容如下,层次结构未知: dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}} 我找到了学习如何递归的方法,但是我很难修改代码以获得我想要的,这是一个从顶层到死胡同的所有路径的列表 所需输出为: list = ['a,b,c', 'a,b,d', 'a,b,e', 'f,g'] 为了开始实现这一点,我采用了一种方法: hierarchy = [] for parent in dict_
dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
我找到了学习如何递归的方法,但是我很难修改代码以获得我想要的,这是一个从顶层到死胡同的所有路径的列表
所需输出为:
list = ['a,b,c', 'a,b,d', 'a,b,e', 'f,g']
为了开始实现这一点,我采用了一种方法:
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']
这很重要,但不是我想要的。假设您的值总是字典,您可以使用:
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
这将使用第一次调用时生成的共享列表将生成的路径传递回调用方,并为每个递归步骤构建一个路径,以便在遇到空值时将其添加到结果列表中
演示:
路径没有排序,因为字典没有顺序;如果需要,您仍然可以按键进行排序:
for key in sorted(d):
value = d[key]
d.iteritems循环中的值代替for键。下面是一个递归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']
这可能吗?对那是200美元!抱歉。这听起来像是DFS的工作。你能编辑这个问题并描述一下你遇到的困难吗?
['a', 'b', 'c']
['a', 'b', 'e']
['a', 'b', 'd']
['f', 'g']