【问题标题】:find the path of the targeted values in a nested python dictionary and list在嵌套的 python 字典和列表中查找目标值的路径
【发布时间】:2017-12-27 02:03:53
【问题描述】:

我遇到了在嵌套 python 字典和列表中查找目标值路径的问题。 例如,我有以下 dict,我的目标值为“blah blah blah”。

{ "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

但它只能在结果中获取目标值,而不能获取路径。 任何人都可以帮忙吗?非常感谢

【问题讨论】:

标签: python list dictionary nested


【解决方案1】:

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

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')

【讨论】:

  • 非常感谢。我能再问一个问题吗?如果这次我想要的路径不同,我不想要像“nestedlist”-“nestednestedlist”-“keyA”这样的键路径,而是我需要的结果是嵌套列表的键和'id'值沿小路。同样的例子,我的目标值为“xyz”,而我想要的结果是'abcde'-'nestedlist'-'qwerty'-'nestednestedlist'-'xyz'
【解决方案2】:
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)

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多