python - Python Json数据按相同的姓氏分组
问题描述
新手来了 我有一个包含全名、年龄、国家和部门的 Json 数据。通过使用 python,我如何生成一个以姓氏为键的新 Json 格式,并且 Json 数据包含具有相同姓氏的总人数、年龄列表和部门列表?
Json 作为数据
{
"John Jane": {
"age": 30,
"Country": "Denmark",
"Department": "Marketing"
},
"Gennie Jane": {
"age": 45,
"Country": "New Zealand",
"Department": "Finance"
},
"Mark Michael": {
"age": 55,
"Country": "Australia",
"Department": "HR"
},
"Jenny Jane": {
"age": 45,
"Country": "United States",
"Department": "IT"
},
"Jane Michael": {
"age": 27,
"Country": "United States",
"Department": "HR"
},
"Scofield Michael": {
"age": 37,
"Country": "England",
"Department": "HR"
}
}
预期结果:
{
"Michael": {
"count": 3, // number of people that have same last name,
"age": {
"age1": 55,
"age2": 27,
"age3": 37
},
"Country": {
"Country1":"Australia",
"Country2":"United States",
"Country3":"England"
},
"Department": {
"Department1": "HR",
"Department2": "HR",
"Department3": "HR"
},
...
...
...
}
}
解决方案
在我看来,使用dict
'年龄','国家'或'部门'没有必要而且更复杂,使用list
应该更好。
import json
text = """{
"John Jane": {
"age": 30,
"Country": "Denmark",
"Department": "Marketing"
},
"Gennie Jane": {
"age": 45,
"Country": "New Zealand",
"Department": "Finance"
},
"Mark Michael": {
"age": 55,
"Country": "Australia",
"Department": "HR"
},
"Jenny Jane": {
"age": 45,
"Country": "United States",
"Department": "IT"
},
"Jane Michael": {
"age": 27,
"Country": "United States",
"Department": "HR"
},
"Scofield Michael": {
"age": 37,
"Country": "England",
"Department": "HR"
}
}"""
dictionary = json.loads(text)
result = {}
for key, value in dictionary.items():
last_name = key.split()[1]
if last_name in result:
result[last_name]['count'] += 1
result[last_name]['age'].append(value['age'])
result[last_name]['Country'].append(value['Country'])
result[last_name]['Department'].append(value['Department'])
else:
result[last_name] = {'count':1, 'age':[value['age']], 'Country':[value['Country']], 'Department':[value['Department']]}
print(result)
{'Jane': {'count': 3, 'age': [30, 45, 45], 'Country': ['Denmark', 'New Zealand', 'United States'], 'Department': ['Marketing', 'Finance', 'IT']}, 'Michael': {'count': 3, 'age': [55, 27, 37], 'Country': ['Australia', 'United States', 'England'], 'Department': ['HR', 'HR', 'HR']}}
推荐阅读
- google-cloud-platform - http负载均衡器和健康检查
- ios - didSelectRowAt 没有被调用,但委托和数据源已设置
- c# - 如何将泛型类型从视图传递到控制器
- python - 使用一列列表重新采样数据框
- html - 在看似有效的 URL 上违反 Content-Security-Policy
- c# - FromUri 删除参数
- go - 如何从 kubectl describe pods 中检索所有数据
来自集群内 client-go api 调用 - python - Django 将请求发布到详细信息页面 (Id)
- php - 如何在php中设置小数点后最多8位
- python - 无法在 Ubuntu 中的 Python 的 Plotyl 中生成 eps 或 pdf 图表