Объединить определенные значения в массив словаря на основе критерия ключ / значение - PullRequest
0 голосов
/ 30 марта 2020

У меня есть ниже JSON сообщений на форуме. Каким будет pythoni c способ создания результирующих JSON агрегированных положительных / отрицательных оценок для форума?

Вход 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},...]
}

]

Ответы [ 2 ]

0 голосов
/ 30 марта 2020

Не могу придумать другого пути:

posts = inputData['Posting_Stats']['Posts']
postAggregator = {}
for post in posts:
    try:
        postAggregator[post['Forum']]['Positive'] += post.get('Positive',0)
        postAggregator[post['Forum']]['Negative'] += post.get('Negative',0)
    except KeyError:
        postAggregator.update({post['Forum']:{"Positive":post.get('Positive',0), "Negative":post.get('Negative',0)}})

outputData = {"Forum_Stats": []}
for key, value in postAggregator.items():
    outputData['Forum_Stats'].append({"Forum":key , "Positive":value['Positive'],"Negative":value['Negative']})

print(outputData)

Вывод:

{'Forum_Stats': [{'Forum': 'panorama', 'Positive': 2, 'Negative': 0}, {'Forum': 'web', 'Positive': 8, 'Negative': 2}]}
0 голосов
/ 30 марта 2020

Это может быть один из способов решения:

#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}]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...