Add values of same key in a dictionary

Viewed 408

My input is a list and I want to convert it into a dictionary and add all values for the same keys. like in the give example in a random list k has two values 1 and 3 so value of k in dictionary will be {'k':4,'D':2}. And then sort it in alphabetic order

Input: ['k:1','D:2','k:3']
Output {'k':4,'D':2}
dlist = ['k:1','D:2','k:3']
  
dick ={}
for x in dlist:
  key,value = x.split(':')
  dick[key] = int(value)

print(dick)

I have the above code but I don't know how to add two values for k?

3 Answers

This is possible by making dick a defaultdict. So, now you can just += the value.

from collections import defaultdict

dlist = ['k:1','D:2','k:3']
  
dick = defaultdict(int)
for x in dlist:
    key, value = x.split(':')
    dick[key] += int(value)

print(dick)

You can use groupby from itertools to group same values and then sum.

import itertools
a=['k:1','D:2','k:3']
print({k:sum([int(j[1]) for j in v]) for k,v in itertools.groupby([i.split(":") for i in sorted(a)], lambda x: x[0])})

Output

{'D': 2, 'k': 4}
Related