简体   繁体   English

如何从字典中返回所有路径?

[英]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.

相关问题 返回所有可能的路径,并已在Python中构建了一个前置字典 - Return all possible paths, having built a predecessor dictionary in Python 返回 python 字典中所需键的所有路径,而不是首先找到 - Return all paths of desired keys in a python dictionary instead of first found 如何从python字典中找到特定节点到叶节点的所有路径以及前面的节点? - How to find all the paths to a particular node to leaf node and also the preceding nodes from python dictionary? 如何从函数返回所有字典值和键 - How to return all dictionary values and keys from function 如何从字典中返回东西并将它们全部相乘? - How to return stuff from the dictionary and multiply them all? neo4j 如何从选定的起始节点返回所有路径 - neo4j how to return all paths from a selected starting node 返回 n 叉树中从根到叶的所有路径 - RETURN all paths from root to leaf in n-ary tree 如何在python中的字典的所有部分中返回null - How to return null in all section in dictionary in python 递归图遍历:如何生成和返回所有路径? - Recursive graph traversal: how to generate and return all paths? 如何在Python中返回随机二叉树的所有可能路径 - How to return all possible paths of random binary tree in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM