I have a JSON file with this format:
{
"people": [
{
"name": "John Smith",
"age":19,
"member": false
},
{
"name": "John Doe",
"age": 23,
"member": false
},
{
"name": "Michael Johnson",
"age":19,
"member": false
},
{
"name": "Daniel Katz",
"age":17,
"member": false
}
]
}
I need to load it as a Python object and calculate the age average. However, any For loop I tried running on this file after opening the file resulted in some sort of TypeError. Any suggestions on how to perform this?
import json
with open('students.json') as f:
data = json.load(f)
data_people = data['people']
CodePudding user response:
You can use statistics.mean
on your dictionary:
import json
from statistics import mean
with open('students.json') as f:
data = json.load(f)
avg_age = mean(p['age'] for p in data['people'])
output: 19.5
CodePudding user response:
I've run your code and it works fine for me. My Python version is 3.10.2 and my OS is win11. Would you like to elaborate your error message?
CodePudding user response:
get list of peoples and use sum on its age
key:
import json
text = """{
"people": [
{
"name": "John Smith",
"age": 19,
"member": false
},
{
"name": "John Doe",
"age": 23,
"member": false
},
{
"name": "Michael Johnson",
"age": 19,
"member": false
},
{
"name": "Daniel Katz",
"age": 17,
"member": false
}
]
}"""
data = json.loads(text)
# or
# with open('students.json') as f:
# data = json.load(f)
average = lambda l: sum(map(lambda x: x["age"], l ))/ len(l)
print(average(data["people"]))
output: 19.5