我有两个json提要,我将它们合并到一个文件中。事件和用户。我需要从users.json获取平均年龄,以确定访问首页(events.json)的所有不同用户的平均年龄。
示例JSON Feed事件:
"events": [
{
"name": "Added item to cart",
"timestamp": 1422119921,
"user_id": "5a5598f2-f7db-420e-9b8e-52a9ad694bc1"
},
{
"name": "Visited product page",
"timestamp": 1409554014,
"user_id": "4683c9b6-3c8b-4215-a401-a9bbfde833ee"
}
示例用户供稿:
"age": 27,
"gender": "F",
"device": "android"
},
"712ae3b5-fbf0-4d83-9324-adc06af77d3a": {
"age": 34,
"gender": "F",
"device": "android"
},
我是python的新手,我相信下面的代码是正确的,但不确定下一步该怎么做。任何其他帮助将不胜感激。
import json
# Opening JSON file
with open('combined.json') as json_file:
data = json.load(json_file)
# for reading nested data [0] represents
# the index value of the list
print(data['events'][0])
print(data['users'][0])
# for printing the key-value pair of
# nested dictionary for looop can be used
print("\nPrinting nested dicitonary as a key-value pair\n")
for i in data['events']:
print("Name:", i['name'])
for i in data ['users']:
print ("Age:", i['age'])
答案 0 :(得分:0)
您处在正确的轨道上,只需将所有年龄段相加并除以用户数即可。这是这样做的一种方式:
import json
# Opening JSON file
with open('combined.json') as json_file:
data = json.load(json_file)
total_age = 0
counter = 0
for k, v in json.load(data['users']).items():
# Add all the ages
total_age += v['age']
counter += 1
print(total_age / counter)