Add the value of a list of dictionaries with the same key

0

I have a list of dictionaries

lst = [ {'x': 1, 'y': 2}, {'x': 1, 'y': 3 }, {'x': 2, 'y': 2 } ]

Dictionaries always have the same keys and it is the values that change at all times.

Then I would like to add the value of the keys "and" when the key "x" has the same value.

The output would have to give: lst # [{'x': 1, 'y': 5 }, {'x': 2, 'y': 2 }].

    
asked by Yoel Macia Delgado 07.02.2018 в 11:58
source

3 answers

1

One option is to use itertools.groupby to group the dictionaries according to the value of the key 'x' . Done this it is simple to use compression of lists to obtain the final list, adding the values of the key 'y' (and also other keys if they exist):

import itertools
from operator import itemgetter



lst = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3 }, {'x': 2, 'y': 2 }]

grupos = itertools.groupby(sorted(lst, key=itemgetter('x')), key=itemgetter('x'))

res = [{'x': v, 'y': sum(dicc['y'] for dicc in diccs)} for v, diccs in grupos]

print(res) 

The output is [{'x': 1, 'y': 5}, {'x': 2, 'y': 2}] .

    
answered by 07.02.2018 / 13:26
source
1

Another alternative solution:

from collections import defaultdict

lst = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3 }, {'x': 2, 'y': 2 }]

aux = defaultdict(int)
for d in lst:
    aux[d['x']] += d['y']

res = [{'x':k, 'y':v} for (k,v) in res.items()]
    
answered by 07.02.2018 в 18:25
0

I have solved the problem, just like that.

lst = [ {'x': 1, 'y': 2}, {'x': 1, 'y': 3 }, {'x': 2, 'y': 2 } ]

result_list = []
name_dict = {}
for dict_item in lst:
    x = dict_item['x']
    y = dict_item['y']
    if x in name_dict:
        pos = name_dict[x]
        result_list[pos] = {'x':x, 'y': (result_list[pos]['y']+y)}
    else:
        result_list.append(dict_item)
        name_dict[x] = len(result_list) - 1

print result_list
    
answered by 07.02.2018 в 13:12