4

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.

sheldonzy
  • 4,613
  • 9
  • 43
  • 74

2 Answers2

11

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})
Aran-Fey
  • 35,525
  • 9
  • 94
  • 135
5

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})
Sohaib Farooqi
  • 4,999
  • 3
  • 29
  • 41