簡體   English   中英

使用Python字典進行列表理解

[英]List Comprehension With A Python Dict

我正在獲取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"
    }
}

解決此問題的最佳方法是什么?

如果我理解正確,那么您想要的就是將所有值從該字典中提取到一個對象中,就像一個理解列表一樣簡單:

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

如果字典中不存在“實體”鍵,則以上各行將返回一個空列表。 您會得到:

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

如果不能保證每個實體字典中都包含值,則可以使用以下內容。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM