Skip to content
Advertisement

Extracting key and value from tuple of dictionaries (taken from json file) in python

I have a JSON file which is a tuple of multiple dictionaries and I want to extract keys and values from some of them.

The file looks something like this (this is just an example of the structure with random keys and values):

file = 
[
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Bob",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Chloe",
            "bio": "xx",
            "type": "female"
        },
        "ID": "8912",
        "status": "STOPPED"
      }
]

What I want to extract all names (Ana, Bob, Chloe) and their ids something like this:

Ana = 1234,
Bob = 5678

etc.

Whatever that I have already tried gives back attribute errors etc. I am not even sure how to iterate through this correctly so that it takes name and ID because they don’t have the same location (the name is inside element dict).

I even tried converting the file to list.

Advertisement

Answer

Firstly, you must open this JSON file and let the json library parse this file, resulting in a loaded dictionary. See Reading JSON from a file? for more information. Once you have your dictionary, which I’ll call users, you can perform this dictionary comprehension:

import json

# Load the file into a `users` (nested) dictionary
with open("file.json", "r") as f:
    users = json.load(f)

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

which outputs:

{'Ana': '1234', 'Bob': '5678', 'Chloe': '8912'}

Note that this can cause issues if there are people with overlapping names! For example:

# I've simply copied this into the .py file for simplicity.
# You'll want to use the JSON parsing method from the Stack Overflow I linked above.
users = [
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Ana",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    }
]

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

print(name_to_ids)

Outputs:

{'Ana': '5678'}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement