在嵌套的python字典中找到目标值的路径并列出

时间:2017-07-21 06:31:13

标签: python list dictionary nested

我有一个问题是在嵌套的python词典和列表中找到目标值的路径。 例如,我有跟随dict,我的目标价值是"等等等等等等。

{ "id" : "abcde",
  "key1" : "blah",
  "key2" : "blah blah",
  "nestedlist" : [ 
    { "id" : "qwerty",
      "nestednestedlist" : [ 
        { "id" : "xyz",
          "keyA" : "blah blah blah" },
        { "id" : "fghi",
          "keyZ" : "blah blah blah" }],
      "anothernestednestedlist" : [ 
        { "id" : "asdf",
          "keyQ" : "blah blah" },
        { "id" : "yuiop",
          "keyW" : "blah" }] } ] } 

我想要的是嵌套字典和列表中此值的路径。 " nestedlist" - " nestednestedlist" - " keyA"

我从Find all occurrences of a key in nested python dictionaries and lists找到了这段代码 并做了一些改变:

def find(key,dic_name):
    if isinstance(dic_name, dict):
        for k,v in dic_name.items():          
            if k == 'name' and v == key:
                yield v
            elif isinstance(v,dict):
                for result in find(key,v):
                    yield result
            elif isinstance(v,list):
                for d in v:
                    for result in find(key,d):
                        yield result

但它只能获得结果中的目标值,而不能获得路径。 有人可以帮忙吗?非常感谢

2 个答案:

答案 0 :(得分:3)

对您链接的代码进行微小更改会产生结果:

def fun(dct, value, path=()):

    for key, val in dct.items():
        if val == value:
            yield path + (key, )
    for key, lst in dct.items():
        if isinstance(lst, list):
            for item in lst:
                for pth in fun(item, value, path + (key, )):
                    yield pth

输入内容:

for item in fun(dct, value='blah blah blah'):
    print(item)

# ('nestedlist', 'nestednestedlist', 'keyA')
# ('nestedlist', 'nestednestedlist', 'keyZ')

在您的评论后更新:代码的微小更改可以执行您想要的操作:

def fun(dct, value, path=()):

    for key, val in dct.items():
        if val == value:
            yield path + (val, )
    for key, lst in dct.items():
        if isinstance(lst, list):
            for item in lst:
                for pth in fun(item, value, path + (dct['id'], key, )):
                    yield pth

示例:

for item in fun(dct, value='xyz'):
    print(item)
# ('abcde', 'nestedlist', 'qwerty', 'nestednestedlist', 'xyz')

答案 1 :(得分:0)

def get_fun(example, value path = None):
    if path is None:
        path = []
    if example == value:
        print path
    elif isinstance(example, dict):
        for key in example.keys():
            path.append(key)
            get_fun(example[key], path)
            path.pop()
    elif isinstance(example, list):
        for i in example:
            get_fun(i, path)