hackerman
hackerman

Reputation: 1291

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?

Upvotes: 0

Views: 61

Answers (2)

Kyle
Kyle

Reputation: 1066

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)

Upvotes: 0

BPL
BPL

Reputation: 9863

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

Upvotes: 2

Related Questions