P
P
pcdesign2020-04-21 20:56:13
Python
pcdesign, 2020-04-21 20:56:13

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 
  }
]


I would like to receive:

[
  {
    "id":"1",
    "qty":8
  },
  {
    "id":"2",
    "qty":2 
  },
  {
    "id":"3",
    "qty":10 
  },
]


That is, id became unique and qty added.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-21
@pcdesign

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()]

UPD: Updated the solution to strictly match the format of the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question