返回python词典中所需键的所有路径,而不是首先找到的键

问题描述 投票:1回答:1

我正在尝试查找字典中所有出现的键。当前,我已经找到了如何创建仅打印第一个生成器的生成器,但是我不确定如何将所有这些返回到对象或以某种方式能够使用生成器理解。如何将所有预期数据返回到可用对象?


t = {'a': 1,
     'b': {'f': 'asfdsf'},
     'c': 3,
     'd': [
        {'a': 1,
         'b': 2,
         'c': 
            {'e': 1},
         'd': 
            {'e': 55}}],
     'g': 2}

def niah(haystack, needle, path=None):
    if path is None:
        path = []
    if isinstance(haystack, dict):
        if needle in haystack:
            #print(path)
            path.append(needle)
            return(path)
        for k, v in haystack.items():
            result = niah(v, needle, path + [k])
            if result is not None:
                return result
    elif isinstance(haystack, list):
        for idx, v in enumerate(haystack):
            result = niah(v, needle, path + [idx])
            if result is not None:              
                return result

输出:

>>> niah(t, 'e'))
['d', 0, 'c', 'e']

所需:

>>> niah(t, 'e'))
[['d', 0, 'c', 'e'], ['d', 0, 'd', 'e']] # or some kind object accessible by iteration, aka generator

屈服的路径似乎只会使生成器陷入无限循环。

python dictionary search path generator
1个回答
0
投票

定义全局变量pathlist=[]。而不是返回,而只需返回pathlist.append(path)(或result等)。

© www.soinside.com 2019 - 2024. All rights reserved.