How to extract inner dictionary key/value into a new dictionary in Python?

Viewed 49

Given this dictionary:

{
    "movies": {
        "action": [
            {
                "title": "Movie A",
                "score": 9.7
            },
            {
                "title": "Movie B",
                "score": 7.0
            }
        ]
    }
}

How would you extract score and put it in a new dictionary keyed off title like below?

{
    "Movie A": 9.7,
    "Movie B": 7.0
}

I'm able to do it using traditional loops, but I'm hoping there is a more efficient way in Python.

1 Answers

First of all, I guess you are coming from a Javascript or similar background. This data structure is called a dictionary (object is something else) and the inner structures are lists (not arrays) in Python land.

Assuming that your dictionary is named d you can use a dictionary comprehension:

print({e["title"]: e["score"] for e in d["movies"]["action"]})
Related