Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting JSON list to dictionary

I am using python and have the following JSON block, json_player, which is stored as a list:

[
    {
        "id": "name",
        "value": "john"
    },
    {
        "id": "sport",
        "value": "baseball"
    },
    {
        "id": "age",
        "value": "20"
    }
]

Note that this is the resulting block from:

json_object = json.loads(df['customFields'])
json_player = json_object['player']

I know that I can access individual strings within json_player using the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

json_player[0]['value']

Which would return the string john.

However, I would like to be able to call individual key-value pairs by name, rather than index, in order to protect myself if underlying JSON order changes. For example:

json_player['name']

would return john. Can anyone tell me how I would do this?

>Solution :

You can easily construct the dictionary using a dict comprehension:

data = {
    item["id"]: item["value"]
    for item in json_player
}
print(data)
# => {'name': 'john', 'sport': 'baseball', 'age': '20'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading