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

2024-05-14 04:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

关于这个问题有很多问题,但就我而言,这些问题是行不通的。我正在尝试查找给定目标键和值对的嵌套字典。我的递归函数返回none(修复后,max depth recursive error)。你知道吗

def recursive_lookup(k, sv, d):
    if k in d: return d[k]
    for v in d.values():
        if isinstance(v, dict):
            a = recursive_lookup(k, sv, v)
            if a == sv:
                if a is not None:
                    return d
    return None


def run():
    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}}

    returned_value = recursive_lookup("FocusPosition", "+000000002097.2550", maly)
    print(returned_value)


run()

如果我把return d改成recursive_lookup(k, sv, d),它也不起作用。 它本应归还苹果词典,但却一本也没有归还。你知道吗

我怎样才能解决那个问题?你知道吗


Tags: runinnone目标returnifvaluedef
3条回答

此示例代码在字典层次结构中执行递归搜索。所以我猜它可能与你想要的相符:

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

编辑:修改西尔维斯特评论后的代码

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

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

下面是一个更容易验证的版本,它使用一个简单的字典,不使用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'}

我认为问题是当您第二次调用recursive\u search()时 它只是一直在同一个字典中寻找sv,而这个字典是maly,它不会在其他字典中搜索更深的内容,这就是为什么它不会返回None

相关问题 更多 >