![]() |
VOOZH | about |
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counter.update() method.
The Counter.update() method updates the counts of elements in a Counter object based on the elements provided in an iterable or another Counter object. It takes an iterable or a mapping (such as another Counter) as its argument and increments the counts of elements accordingly.
Counter.update(iterable_or_mapping)Below are some of the examples by which we can understand about Counter.update() method in Python:
In this example, the counts of 'apple' and 'banana' are updated based on the elements in the fruits list.
Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1})
In this example, the counts of elements in counter1 are updated based on the counts in counter2.
Combined Counter: Counter({'b': 6, 'a': 4, 'c': 2})
In this example, we use a generator expression to convert each word to lowercase before updating the counts in the word_counter.
Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1})