sheldonzy
sheldonzy

Reputation: 5961

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.

Upvotes: 5

Views: 4579

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43166

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})

Upvotes: 11

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

You can also use dict unpacking

from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
Counter({**a, **b})
Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})

Upvotes: 5

Related Questions