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

2024-02-27

关于这个问题有很多问题,但就我而言,它们不起作用。我试图找到一个给定目标键和值对的嵌套字典。我的递归函数没有返回任何内容(修复后,最大深度递归错误)。

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 to recursive_lookup(k, sv, d)它也不起作用。 它应该返回maly字典,但它返回 None 。

我该如何解决这个问题?


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

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'}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐