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.
So I would like to sum the value of the keys "y" when the key "x" has the same value.
The output should give:lst # [{'x': 1, 'y': 5 }, {'x': 2, 'y': 2 }].
One option is to use
itertools.groupby
to group the dictionaries based on the value of the key'x'
. Once this is done, it is simple to use list compression to obtain the final list, adding the values of the key'y'
(and also other keys if they exist):The output is
[{'x': 1, 'y': 5}, {'x': 2, 'y': 2}]
.Another workaround:
I have solved the problem, like so.