-2

How to add the values with same keys. Is there any hack can do at the line like sum(int(v)))

m = {'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}
l = []
for i in m:
    #print (i)
    for j in i.items():
        l.append(j)
from collections import defaultdict
f = defaultdict(list)
for k, v in l:
    f[k].append(int(v)) #hack
for i,j in f.items():
    print (i,sum(j)) 

My out

Rash 4
Manjeet 5
Akash 7

My expected out

{'Rash': 4, 'Manjeet': 5, 'Akash': 7}
bharatk
  • 4,202
  • 5
  • 16
  • 30

1 Answers1

1

You can use collections.Counter for a simpler approach:

from collections import Counter
c = Counter()
for d in m:
    c += d

print(c)
# Counter({'Akash': 7, 'Manjeet': 5, 'Rash': 4})

Or using defaultdict:

out = defaultdict(int)
for d in m:
    for k,v in d.items():
        out[k] += v

print(out)
# defaultdict(<class 'int'>, {'Rash': 4, 'Manjeet': 5, 'Akash': 7})
yatu
  • 86,083
  • 12
  • 84
  • 139