python - 根据键/值标准聚合字典数组中的某些值
问题描述
我有以下论坛帖子的 JSON。创建每个论坛汇总的正面/负面评级的结果 JSON 的 pythonic 方式是什么?
输入Json:
{"Posting_Stats":{
"Posts":[
{
"Date":"2020-03-29 12:41:00",
"Forum":"panorama",
"Positive":2,
"Negative":0
},
{
"Date":"2020-03-29 12:37:00",
"Forum":"web",
"Positive":6,
"Negative":0
},
{
"Date":"2020-03-29 12:37:00",
"Forum":"web",
"Positive":2,
"Negative":2
},...]}
输出应该是:
{"Forum_Stats" : [{"Forum" : "panorama",
"Positive":2,
"Negative":0},
{"Forum" : "web",
"Positive":8,
"Negative":2},...]
}
]
解决方案
这可能是一种解决方法:
#taking the input in a dictionary
d = {"Posting_Stats":{
"Posts":[
{
"Date":"2020-03-29 12:41:00",
"Forum":"panorama",
"Positive":2,
"Negative":0
},
{
"Date":"2020-03-29 12:37:00",
"Forum":"web",
"Positive":6,
"Negative":0
},
{
"Date":"2020-03-29 12:37:00",
"Forum":"web",
"Positive":2,
"Negative":2
}]}}
#iterating over the values to get their some on the basis of forum as key
temp = {}
for i in d.get('Posting_Stats').get('Posts'):
if temp.get(i.get('Forum')) == None:
temp[i.get('Forum')] = {}
temp[i.get('Forum')]['Positive'] = 0
temp[i.get('Forum')]['Negative'] = 0
temp[i.get('Forum')]['Positive']+=i.get('Positive')
temp[i.get('Forum')]['Negative']+=i.get('Negative')
最后将输出转换为所需的格式
output = [{'Forum': i , **temp[i] } for i in temp]
print(output)
#[{'Forum': 'panorama', 'Positive': 2, 'Negative': 0},
#{'Forum': 'web', 'Positive': 8, 'Negative': 2}]
推荐阅读
- c# - C# 计算字符串表达式并返回结果
- python - 有没有办法检测二值化图像中的对象?
- python - 如何从@commands.has_role() 获取“错误”消息
- sql-server - MS SQL Server:防止执行计划过时
- javascript - 客户端使用 CryptoJS 计算的 MD5 哈希与终端计算不同
- javascript - JavaScript 函数未发布
- mysql - 找出所有与克里斯托弗·诺兰合作的电影比其他任何导演都多的演员
- microservices - 在具有事件源的微服务中,我应该将命令或事件保存到服务数据库还是应该是一个大数据库?
- octobercms - 如何使用 OctoberCms 回滚?
- python - 从数据框列值创建一个函数并插入另一列的空白元素