首页 > 解决方案 > 根据键/值标准聚合字典数组中的某些值

问题描述

我有以下论坛帖子的 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},...]
}

]

标签: pythonarraysjsonlistdictionary

解决方案


这可能是一种解决方法:

#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}]

推荐阅读