I'm stumbled against a simple problem that I cannot figure out.
I have a list of objects saved in a json file. Once converted into Python they give me something like this:
data = [
{"id": 1, "value": 3},
{"id": 2, "value": 1},
{"id": 3, "value": 5},
{"id": 1, "value": 1},
{"id": 1, "value": 2},
{"id": 3, "value": 2},
{"id": 1, "value": 3}
]
I'm trying to have only one object / dictionary per unique 'id'. In other words I'm trying to obtain the following result:
[{"id": 1, "value": 9}, {"id": 2, "value": 1}, {"id": 3, "value": 7}]
Obviously, I could do it the long way around:
foo = list(set([item["id"] for item in data]))
newList = []
for i in foo:
bar = {"id": i, "value": 0}
for x in data:
if x['id'] == i:
bar['value'] += x['value']
newList.append(bar)
However I'm worried about this triple-nested loop which might slow down the process considerably with large datasets.
I'm familiar with sum(d.values())
and I've seen the question on collection's Counters, but these do not work in my case.
Any ideas how the desired result can be obtained ?