python - 获取字典上存在特定键值对的列表

标签 python json list dictionary

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

 [
    {
        "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”的字典?可以从字典中检索到吗?键“服装”可能出现在列表的任何部分。

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

最佳答案

您可以使用以下代码获取 NameClothing 的每个项目:

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']

关于python - 获取字典上存在特定键值对的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64565425/

相关文章:

javascript - 如何删除嵌套的 JSON 元素?

c# - 如何在对象列表中查找单个项目?

python - 列表理解与循环——我不明白什么?

python - 将列添加到常规数据帧中的日期时间索引数据帧

python - 使用字典创建数据框

python - 我如何使用 '__set__'

javascript - 文本框值在 angularjs 中返回空

python - 删除 pandas 中的所有行,直到找到特定字符串,然后停止删除

java - 如何从 servlet 获取 JSON 对象?

python - 更改字符串列表中的字符串