[英]How to return all paths from a dictionary?
Lets say i have this dictionary可以说我有这本词典
obj = {'layerA1':'string','layerA2':{'layerB1':{'layerC1':{},'layerC2':{}},
'layerB2':{}}}
i would need to return我需要回来
['layerA2','layberB1','layerC1']
['layerA2','layerB1','layerC2']
['layerA2','layerB2']
It should work regardless of how deep the dictionary gets.无论字典有多深,它都应该起作用。 Currently trying with some recursive functions but i can't seem to get it right.
目前正在尝试使用一些递归函数,但我似乎无法正确处理。 What i currently have is this:
我目前拥有的是这样的:
obj = {'layerA1':'string','layerA2':{'layerB1':{'layerC1':{},'layerC2':{}},
'layerB2':{}}}
hierarchy_list = []
def find_hierachy(param):
some_list = []
for key, value in param.items():
if type(param[key]) is dict:
some_list.append(key)
hierarchy_list.append(some_list)
find_hierachy(param[key])
find_hierachy(obj)
print(hierarchy_list)
[['layerA2'], ['layerB1', 'layerB2'], ['layerC1', 'layerC2'], ['layerC1', 'layerC2'], ['layerB1', 'layerB2']]
I don't know how to get it to return each hierarchical path made of keys我不知道如何让它返回由键组成的每个分层路径
As you noticed in your code, you need to keep track of the path you have taken sofar, this is often referred to as the prefix.正如您在代码中注意到的那样,您需要跟踪到目前为止所采用的路径,这通常称为前缀。 By storing the prefix and passing it along, we can keep track of the previous keys.
通过存储前缀并传递它,我们可以跟踪以前的键。 An important thing to keep in mind is that default variables in python should be immutable (tuples) unless you know what happens with mutable objects while using recursion.
要记住的重要一点是,python 中的默认变量应该是不可变的(元组),除非您知道在使用递归时可变对象会发生什么。
answer = []
def hierarchy(dictionary, prefix=()):
for key, value in dictionary.items():
if isinstance(value, dict) and value:
hierarchy(value, (*prefix, key))
else:
answer.append((*prefix, key))
If you want the final answer to be a list, you can loop over the answers
and cast them to a list, or send the list as prefix.如果您希望最终答案是一个列表,您可以遍历
answers
并将它们转换为一个列表,或者将列表作为前缀发送。 This requires us to copy the list to the next level of the hierarchy.这需要我们将列表复制到层次结构的下一级。 Which is done using
[*prefix, key]
which makes a new copy of the list.这是使用
[*prefix, key]
完成的,它会生成列表的新副本。
obj = {'layerA1': 'string', 'layerA2': {'layerB1': {'layerC1': {}, 'layerC2': {}},
'layerB2': {}}}
if __name__ == '__main__':
answer = []
def hierarchy(dictionary, prefix=None):
prefix = prefix if prefix is not None else []
for key, value in dictionary.items():
if isinstance(value, dict) and value:
hierarchy(value, [*prefix, key])
else:
answer.append([*prefix, key])
hierarchy(obj)
print(answer)
Output输出
[['layerA1'], ['layerA2', 'layerB1', 'layerC1'], ['layerA2', 'layerB1', 'layerC2'], ['layerA2', 'layerB2']]
Note:笔记:
Type checking can be done using isinstance(obj, type)
, which is the preferred way above type(obj) is type
.类型检查可以使用
isinstance(obj, type)
来完成,这是type(obj) is type
上面的首选方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.