首页 > 解决方案 > 在有特定键值对的列表中获取字典

问题描述

假设我在列表中有这本字典:

 [
    {
        "Name": "Person",
        "Confidence": 97.56156921386719,
        "Instances": [
            {
                "BoundingBox": {
                    "Width": 0.6137702465057373,
                    "Height": 0.9175498485565186,
                    "Left": 0.22297996282577515,
                    "Top": 0.0739903450012207
                },
                "Confidence": 94.51961517333984
            },
            {
                "BoundingBox": {
                    "Width": 0.46570318937301636,
                    "Height": 0.6405649781227112,
                    "Left": 0.11447866261005402,
                    "Top": 0.34079012274742126
                },
                "Confidence": 82.2153549194336
            }
        ],
        "Parents": []
    },
    {
        "Name": "Human",
        "Confidence": 97.56156921386719,
        "Instances": [],
        "Parents": []
    },
    {
        "Name": "Clothing",
        "Confidence": 91.08417510986328,
        "Instances": [],
        "Parents": []
    }
    }]

如何仅检索具有键值“名称”:“服装”的字典?是否可以从字典中检索它?“服装”键可能出现在列表的任何部分。

    {
        "Name": "Clothing",
        "Confidence": 91.08417510986328,
        "Instances": [],
        "Parents": []
    }
  

标签: pythonjsonlistdictionary

解决方案


您可以使用以下代码获取具有Name的每个项目Clothing

names = [
    {
        "Name": "Person",
        "Confidence": 97.56156921386719,
        "Instances": [
            {
                "BoundingBox": {
                    "Width": 0.6137702465057373,
                    "Height": 0.9175498485565186,
                    "Left": 0.22297996282577515,
                    "Top": 0.0739903450012207
                },
                "Confidence": 94.51961517333984
            },
            {
                "BoundingBox": {
                    "Width": 0.46570318937301636,
                    "Height": 0.6405649781227112,
                    "Left": 0.11447866261005402,
                    "Top": 0.34079012274742126
                },
                "Confidence": 82.2153549194336
            }
        ],
        "Parents": []
    },
    {
        "Name": "Human",
        "Confidence": 97.56156921386719,
        "Instances": [],
        "Parents": []
    },
    {
        "Name": "Clothing",
        "Confidence": 91.08417510986328,
        "Instances": [],
        "Parents": []
    }
]

for name in names:
    if name['Name'] == 'Clothing':
        print(name)

如果您希望它简短,可以使用以下代码:

x = [y for y in names if name['Name'] == 'Clothing']

推荐阅读