we have this dict and this list
mydict={a:1,b:1}
mylist=[a,b,a,c]
I want to merge that list into the dict like this:
mydict={a:3,b:2,c:1}
we have this dict and this list
mydict={a:1,b:1}
mylist=[a,b,a,c]
I want to merge that list into the dict like this:
mydict={a:3,b:2,c:1}
You can do it by
for item in mylist:
try:
mydict[item] += 1
except KeyError:
mydict[item] = 1
I would use Counters for this.
from collections import Counter
mydict={'a':1,'b':1}
mylist=['a','b','a','c']
c1 = Counter(mydict)
c2 = Counter(mylist)
mynewdict = c1 + c2
Counter({'a': 3, 'b': 2, 'c': 1})
If you need the newdict as an actual dict and not a counter then:
mynewdict = dict(mynewdict)
A companion to @meTchaikovsky's answer.
for item in mylist:
mydict[item] = mydict.get(item, 0) + 1