Skip to content
Advertisement

Python: Get all values of a specific key from json file

Im getting the json data from a file:

 "students": [
     {
        "name" : "ben",
        "age" : 15
     },
     {
        "name" : "sam",
        "age" : 14
     }
  ]
}

here’s my initial code:

def get_names():
  students = open('students.json')
  data = json.load(students)

I want to get the values of all names

[ben,sam]

Advertisement

Answer

you need to extract the names from the students list.

data = {"students": [
     {
        "name" : "ben",
        "age" : 15
     },
     {
        "name" : "sam",
        "age" : 14
     }
  ]
       }

names = [each_student['name'] for each_student in data['students']]

print(names) #['ben', 'sam']
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement