0

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?

Jannik
  • 399
  • 2
  • 5
  • 22
  • 1
    Is the structre of the JSON always like this (the desired keys in the "2nd level"?) Or can it be that "Y" appears alongside "A" and "B"? or inside "X"? – Jan Stránský Aug 22 '20 at 09:34
  • The structure is always the same, the key will always be in the same level. – Jannik Aug 22 '20 at 09:45

1 Answers1

4

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']
balderman
  • 22,927
  • 7
  • 34
  • 52