Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 递归定位包含目标键和值的嵌套字典_Python_Python 3.x_Dictionary_Recursion - Fatal编程技术网

Python 递归定位包含目标键和值的嵌套字典

Python 递归定位包含目标键和值的嵌套字典,python,python-3.x,dictionary,recursion,Python,Python 3.x,Dictionary,Recursion,关于这个问题有很多问题,但在我的情况下,它们不起作用。我正在尝试查找给定目标键和值对的嵌套字典。我的递归函数返回无(修复后,最大深度递归错误) 如果我将返回d更改为递归查找(k,sv,d)它也不起作用。 它应该返回maly字典,但没有返回 如何解决该问题?此示例代码在字典层次结构中执行递归搜索。因此,我想这可能与您正在寻找的内容相符: def rec_search(key, dic): if key in dic: return dic[key] for d in dic.val

关于这个问题有很多问题,但在我的情况下,它们不起作用。我正在尝试查找给定目标键和值对的嵌套字典。我的递归函数返回无(修复后,最大深度递归错误)

如果我将
返回d
更改为
递归查找(k,sv,d)
它也不起作用。 它应该返回maly字典,但没有返回


如何解决该问题?

此示例代码在字典层次结构中执行递归搜索。因此,我想这可能与您正在寻找的内容相符:

def rec_search(key, dic):
  if key in dic:
    return dic[key]
  for d in dic.values():
    if isinstance(d, dict):
      val = rec_search(key, d)
      if val is not None: return val
  return None

maly = {1:'a',
        2:'b',
        3:{4:'d',
           5:'e',
           6:{7:'g',
              8:'h'}
          },
        9:{10:'i',
           11:'j',
           12:{13:'l',
               14:'m'}
          }
        }

print(rec_search(2,maly)) # --> 'b'
print(rec_search(7,maly)) # --> 'g'
print(rec_search(10,maly)) # --> 'i'
print(rec_search(15,maly)) # --> None

编辑:在Sylvester的评论后更正了代码

这是正确的想法,但匹配的结果没有正确地传递到调用堆栈。您还可以通过检查同一调用帧上的键和值来简化逻辑——这还应该消除目标键值位于dict顶层的错误(没有可用于检查值的前一帧)

下面是一个更容易验证的版本,它使用一个简单的字典,不使用3.8赋值表达式:

def recursive_lookup(target_key, target_val, dictionary):
    if target_key in dictionary and dictionary[target_key] == target_val:
        return dictionary

    for value in dictionary.values():
        if isinstance(value, dict):
            result = recursive_lookup(target_key, target_val, value)

            if result: return result

if __name__ == "__main__":
    dictionary = {
        "a": "foo",
        "b": {
            "c": "bar",
            "d": "baz",
            "e": {
                "f": "quux",
                "g": "garply"
            }
        }
    }

    print(recursive_lookup("c", "bar", dictionary)) # => {'c': 'bar', 'd': 'baz', 'e': {'f': 'quux', 'g': 'garply'}}
    print(recursive_lookup("g", "garply", dictionary)) # => {'f': 'quux', 'g': 'garply'}

我认为问题在于第二次调用递归搜索()时
它只是一直在同一个字典中查找sv,它是maly,而在其余的字典中没有搜索更深的内容,这就是为什么它返回None

maly的数据类型是什么maly我建议发布一篇文章并解释这段代码应该做什么。谢谢@ksooklallpost编辑@ggorlenThanks!期望的结果是否应该是嵌套dict包含的任何一个
“FocusPosition”、“+00000000 2097.2550”
作为直接键值对?有时值得使用一个简单的示例,它清楚地显示了所需的行为,使用小型键/值对(如
“a”
“b”
)以及两个简单的嵌套层。如果在同一级别中有两个DICT,则无论是正匹配还是正匹配,都将从第一个DICT返回结果not@Sylwester:啊!你完全正确。我已经更正了代码。谢谢我认为这不符合OP的意图。我认为OP想要给出一个键和一个值,并获得包含该键-值对的字典。这个解决方案是哪个python版本?我现在有py3.6了。我将更新到3.6。让我知道这是否符合你的意图。
def recursive_lookup(target_key, target_val, dictionary):
    if target_key in dictionary and dictionary[target_key] == target_val:
        return dictionary

    for value in dictionary.values():
        if isinstance(value, dict):
            if result := recursive_lookup(target_key, target_val, value): 
                return result

if __name__ == "__main__":
    maly = {'_id': "ObjectId('5def7e8c4802b906dd067f97')", 'METADATA': {'Tags': {'AcquisitionTime': '2019-02-05T15:59:37.5862118Z', 'ImageScaling': {'ImageScaling': {'ImagePixelSize': '4.54,4.54'}}, 'DetectorState': {'CameraState': {'ApplyCameraProfile': 'false', 'ApplyImageOrientation': 'true', 'ExposureTime': '2200000', 'Frame': '0,0,2752,2208', 'ImageOrientation': '3'}}, 'StageXPosition': '+000000141526.5820', 'StageYPosition': '+000000189329.5000', 'FocusPosition': '+000000002097.2550', 'RoiCenterOffsetX': '+000000000000.0000', 'RoiCenterOffsetY': '+000000000000.0000'}, 'DataSchema': None, 'AttachmentSchema': None}}
    print(recursive_lookup("FocusPosition", "+000000002097.2550", maly))
def recursive_lookup(target_key, target_val, dictionary):
    if target_key in dictionary and dictionary[target_key] == target_val:
        return dictionary

    for value in dictionary.values():
        if isinstance(value, dict):
            result = recursive_lookup(target_key, target_val, value)

            if result: return result

if __name__ == "__main__":
    dictionary = {
        "a": "foo",
        "b": {
            "c": "bar",
            "d": "baz",
            "e": {
                "f": "quux",
                "g": "garply"
            }
        }
    }

    print(recursive_lookup("c", "bar", dictionary)) # => {'c': 'bar', 'd': 'baz', 'e': {'f': 'quux', 'g': 'garply'}}
    print(recursive_lookup("g", "garply", dictionary)) # => {'f': 'quux', 'g': 'garply'}