Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 634
sheldonzy Avatar asked Dec 03 '22 20:12

sheldonzy


2 Answers

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})
like image 200
Aran-Fey Avatar answered Dec 06 '22 11:12

Aran-Fey


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})
like image 25
Sohaib Farooqi Avatar answered Dec 06 '22 11:12

Sohaib Farooqi