0

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}
keepAlive
  • 6,369
  • 5
  • 24
  • 39
Kori
  • 15
  • 3

3 Answers3

1

You can do it by

for item in mylist:
    try:
        mydict[item] += 1
    except KeyError:
        mydict[item] = 1
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34
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)

PyPingu
  • 1,697
  • 1
  • 8
  • 21
1

A companion to @meTchaikovsky's answer.

for item in mylist:
    mydict[item] = mydict.get(item, 0) + 1

keepAlive
  • 6,369
  • 5
  • 24
  • 39