Search code examples
pythonpython-3.xdictionarycounterpython-collections

Python append Counter to Counter, like Python dictionary update


I have 2 Counters (Counter from collections), and I want to append one to the other, while the overlapping keys from the first counter would be ignored. Like the dic.update (python dictionaries update)

For example:

from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)

So something like (ignore overlapping keys from the first counter):

# a.update(b) 
Counter({'a':4, 'z':1, 'b':2, 'c':3})

I guess I could always convert it to some kind of a dictionary and then convert it back to Counter, or use a condition. But I was wondering if there is a better option, because I'm using it on a pretty large data set.


Solution

  • Counter is a dict subclass, so you can explicitly invoke dict.update (rather than Counter.update) and pass two counters as the arguments:

    a = Counter(a=4, b=0, c=1)
    b = Counter(z=1, b=2, c=3)
    
    dict.update(a, b)
    
    print(a)
    # Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})