Search code examples
python-3.xdictionarymerging-data

How merge a dict and a list and adding more value to it?


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}

Solution

  • A companion to @meTchaikovsky's answer.

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