kyrenia
kyrenia

Reputation: 5565

Elegant way of adding a set to a counter in Python

What is the most elegant way of incrementing a counter by 1 for each element in a set?

For example at the moment i do something like:

from collections import Counter
my_counter = Counter()
my_set = set(["a", "b", "c", "d"])
for item in my_set:
    my_counter[item] += 1

But i was wondering if it possible to 'add' a set to a already existing counter directly?

Upvotes: 10

Views: 8707

Answers (1)

unutbu
unutbu

Reputation: 879501

You could use the update method. update can accept an iterable (e.g. a set) or a mapping (e.g. a dict). Note that update adds to the count; it does not replace the count:

In [7]: my_counter.update(my_set)

In [8]: my_counter
Out[8]: Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})

Or, add another Counter in-place:

In [18]: my_counter += Counter(my_set)

In [19]: my_counter
Out[19]: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})

Upvotes: 15

Related Questions