从python中的深度嵌套字典中获取值

2024-04-26 04:32:32 发布

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

我有一本python词典

{
    'SearchedFaceBoundingBox': {
        'Width': 0.21481677889823914,
        'Height': 0.4107130169868469,
        'Left': 0.4110604524612427,
        'Top': 0.14158998429775238,
        },
    'SearchedFaceConfidence': 99.99972534179688,
    'FaceMatches': [{'Similarity': 99.98224639892578, 'Face': {
        'FaceId': '135c758c-d2f0-47e4-9f2c-5c6194063dd6',
        'BoundingBox': {
            'Width': 0.4479779899120331,
            'Height': 0.563962996006012,
            'Left': 0.6124510169029236,
            'Top': 0.07734870165586472,
            },
        'ImageId': 'c58935a2-384e-307a-b2d2-060821f035df',
        'ExternalImageId': '0000000028037c08_1545579782.jpg',
        'Confidence': 99.9999008178711,
        }}, {'Similarity': 99.8758773803711, 'Face': {
        'FaceId': '89c29bd7-44bf-414c-8911-9375d319a408',
        'BoundingBox': {
            'Width': 0.3835090100765228,
            'Height': 0.7424889802932739,
            'Left': 0.28391098976135254,
            'Top': -0.17907099425792694,
            },
        'ImageId': 'be3e2c55-f434-3638-8391-a97e74e94604',
        'ExternalImageId': '0000000028037c08_1545573336.jpg',
        'Confidence': 99.9999008178711,
        }}],
    'FaceModelVersion': '4.0',
    'ResponseMetadata': {
        'RequestId': '571d7684-06d5-11e9-bda1-41e0984ad764',
        'HTTPStatusCode': 200,
        'HTTPHeaders': {
            'content-type': 'application/x-amz-json-1.1',
            'date': 'Sun, 23 Dec 2018 17:08:16 GMT',
            'x-amzn-requestid': '571d7684-06d5-11e9-bda1-41e0984ad764',
            'content-length': '1947',
            'connection': 'keep-alive',
            },
        'RetryAttempts': 0,
        },
    }

从这里我只想提取ExternalImageId。我尝试了以下代码:

import re

def get_path(dct, path):
    for i, p in re.findall(r'(\d+)|(\w+)', path):
        dct = dct[p or int(i)]
    return dct

value = get_path(f, "FaceMatches[0].Face.ExternalImageId")

虽然这样做有效,但它只获取第一个匹配项,如果我删除[0],就会得到一个错误TypeError: list indices must be integers or slices, not str。你知道吗

如何检索所有ExternalImageId。我在用Python3。你知道吗


Tags: pathtopwidthleftdctfacejpgconfidence
1条回答
网友
1楼 · 发布于 2024-04-26 04:32:32

这是一个dict,为什么是RegEx?你能做到的

data = {...}

for match in data['FaceMatches']:
    print(match['Face']['ExternalImageId'])

输出

0000000028037c08_1545579782.jpg
0000000028037c08_1545573336.jpg

编辑,以展开/解释答案:dict has element with key'FaceMatches'。此键的值是一个列表。你需要遍历这个列表。其中的每个元素都是一个不同的面,也是dict。您需要键'Face',它将为您提供另一个dict作为值。您希望从后面的dict中获取键'ExternalImageId'的值。你知道吗

相关问题 更多 >

    热门问题