简体   繁体   中英

List Comprehension With A Python Dict

I'm taking JSON structured data and storing it in a Python dict called output I know I could normally use .get('value') to find the value. However what I'm not clear on is how to use .get() inside a part of a list that isn't always populated.

My 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"
        }
    ],
    "intent": {
        "confidence": 0.9765,
        "name": "test_intent"
}
}

I'm trying to write a statement that stores all value , in this case razor , pool , and Pet in an object. It is also possible that entities isn't populated, only intent .

In which case the output could simply be:

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

What's the best way to approach this?

If I've understood correctly, what you want is to extract all values into an object from that dictionary, that'd be as simple as a comprehension list such as:

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

The above lines would return an empty list in case the "entities" key wouldn't exist in the dictionary. You'd get:

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

If value isn't guaranteed to be in each entity dictionary you can use the following.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM