用pythondi列出理解

2024-06-10 15:22:33 发布

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

我获取JSON结构化数据并将其存储在名为output的Python dict中。我知道我通常可以使用.get('value')来查找值。然而,我不清楚的是如何在一个不总是填充的列表的一部分中使用.get()

我的输出:

{
    "entities": [
        {
            "end": 3,
            "entity": "pet",
            "extractor": "ner_crf",
            "processors": [
                "ner_synonyms"
            ],
            "start": 0,
            "value": "Pet"
        },
        {
            "end": 8,
            "entity": "aquatic_facility",
            "extractor": "ner_crf",
            "start": 4,
            "value": "pool"
        },
        {
            "end": 14,
            "entity": "toiletries",
            "extractor": "ner_crf",
            "start": 9,
            "value": "razor"
        }
    ],
    "intent": {
        "confidence": 0.9765,
        "name": "test_intent"
}
}

我试图编写一个语句来存储对象中的所有value,在本例中是razorpoolPet。也有可能entities没有填充,只有intent

在这种情况下,输出可以是:

{
    "entities": [],
    "intent": {
        "confidence": 0.9765,
        "name": "test_intent"
    }
}

最好的方法是什么


Tags: namegetvaluestartendrazorentityentities
2条回答

如果不能保证值在每个实体字典中,那么可以使用以下方法

output = {
    "entities": [
        {
            "end": 3,
            "entity": "pet",
            "extractor": "ner_crf",
            "processors": [
                "ner_synonyms"
            ],
            "start": 0,
            "value": "Pet"
        },
        {
            "end": 8,
            "entity": "aquatic_facility",
            "extractor": "ner_crf",
            "start": 4,
            "value": "pool"
        },
        {
            "end": 14,
            "entity": "toiletries",
            "extractor": "ner_crf",
            "start": 9,
            "value": "razor"
        },
        {
            "end": 14,
            "entity": "toiletries",
            "extractor": "ner_crf",
            "start": 9,
        }
],
    "intent": {
        "confidence": 0.9765,
        "name": "test_intent"
    }
}


values = [a.get('value') for a in output.get('entities', []) if 'value' in a]

print(values)

如果我理解正确,您需要的是从字典中将所有值提取到对象中,这就像comprehension list一样简单,例如:

obj = [v["value"] for v in dct.get("entities",[])]
print(obj)

如果字典中不存在“entities”键,上述行将返回一个空列表。你会得到:

['Pet', 'pool', 'razor']

相关问题 更多 >