1

I have a list of dictionaries as shown below:

result = [
    {'so': 'SO1', 'amt':250},
    {'so': 'SO2', 'amt':200},
    {'so': 'SO1', 'amt':100}
]

I need to merge it so that the result would be:

result = [
    {'so': 'SO1', 'amt':350},
    {'so': 'SO2', 'amt':200}
]

that is the dictionaries with same SO are merged and their amt is added.

Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
Gopakumar N G
  • 1,775
  • 1
  • 23
  • 40
  • @sshashank124 I think this particular example is a little more complex than the one presented in the question suggested as being duplicated. – skamsie Apr 04 '14 at 10:25
  • @HerrActress, The OP should be able to get enough of an idea from that question and then be able to suite it for his own needs. The point is not to find an __exactly__ similar question but a similar one. Also the point is to learn by practice, having been given quite a related answer. However, if you still believe so, let me know and I will retract my close vote. :) – sshashank124 Apr 04 '14 at 10:31
  • @sshashank124 You are probably right, plus 4 other people that seem to think the same :) – skamsie Apr 04 '14 at 10:36

3 Answers3

3

Collections.counter provides an elegant way to merge dictionaries this way.

from collections import Counter
counters = [Counter({k['so']: k['amt']}) for k in result]
r = sum(counters, Counter())
# Counter({'SO1': 350, 'SO2': 200})
result = [{'so': k, 'amt': r.get(k)} for k in r]
# [{'so': 'SO1', 'amt': 350}, {'so': 'SO2', 'amt': 200}]
spinlok
  • 3,561
  • 18
  • 27
2

My solution:

d = dict()
for so, amt in map(lambda x: (x["so"],x["amt"]), result):
    d[so] = d.get(so, 0) + amt

d is the final dictionary you want. If you have a huge list result, you should take imap instead of map.

Explanation:

map(lambda x: (x["so"],x["amt"]), result) results in the following list:

result = [
    ('SO1', 250),
    ('SO2', 200),
    ('SO1', 100)
]

d.get(so,0) is like d[so] but returns 0 as a default value when d has no key with value so.

Stephan Kulla
  • 4,739
  • 3
  • 26
  • 35
1

Try this..

import collections

data = collections.OrderedDict()
for d in dictlist:
    so = d['so']
    data.setdefault(so, 0)
    data[so] += d['amt']
result = [{'so':k, 'amt': v} for k, v in data.items()]

Hope this helps