Jannik
Jannik

Reputation: 427

Python: Getting all values of a specific key from json

I'm using an API that returns data in JSON format like that:

{
    "ABC": {
        "A": {
            "X": "1",
            "Y": "2",
            "Z": "3",
        },
        "B": {
            "X": "4",
            "Y": "5",
            "Z": "6",
        },
        "C": {
            "X": "7",
            "Y": "8",
            "Z": "9",
        }
    }
}

Now I want to get all values of a specific key in a list, in this simple example for the key "Y", the list should look like this: [2, 5, 8]

What's the easiest way to achieve this in Python?

Upvotes: 0

Views: 2383

Answers (1)

balderman
balderman

Reputation: 23815

Below

data = {
    "ABC": {
        "A": {
            "X": "1",
            "Y": "2",
            "Z": "3",
        },
        "B": {
            "X": "4",
            "Y": "5",
            "Z": "6",
        },
        "C": {
            "X": "7",
            "Y": "8",
            "Z": "9",
        }
    }
}

def get_val(key):
  return [entry[key] for entry in data['ABC'].values()]
  
print(get_val('Y'))

output

['2', '5', '8']

Upvotes: 4

Related Questions