Answer the question
In order to leave comments, you need to log in
How to calculate sums in a list of dictionaries?
Here is a snippet:
[
{
"id":"1",
"qty":6
},
{
"id":"2",
"qty":1
},
{
"id":"1",
"qty":1
},
{
"id":"2",
"qty":1
},
{
"id":"3",
"qty":10
},
{
"id":"1",
"qty":1
}
]
[
{
"id":"1",
"qty":8
},
{
"id":"2",
"qty":2
},
{
"id":"3",
"qty":10
},
]
Answer the question
In order to leave comments, you need to log in
Here's a quicker solution.
from collections import Counter
a = [{'id': '1', 'qty': 6}, {'id': '2', 'qty': 1}, {'id': '1', 'qty': 1}, {'id': '2', 'qty': 1}, {'id': '3', 'qty': 10}, {'id': '1', 'qty': 1}]
c = sum((Counter({d['id']: d['qty']}) for d in a), Counter())
result = [dict(id=k, qty=v) for k, v in c.items()]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question