Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.up
(self, iterable=None, /, **kwds)
| 672 | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 673 | |
| 674 | def update(self, iterable=None, /, **kwds): |
| 675 | '''Like dict.update() but add counts instead of replacing them. |
| 676 | |
| 677 | Source can be an iterable, a dictionary, or another Counter instance. |
| 678 | |
| 679 | >>> c = Counter('which') |
| 680 | >>> c.update('witch') # add elements from another iterable |
| 681 | >>> d = Counter('watch') |
| 682 | >>> c.update(d) # add elements from another counter |
| 683 | >>> c['h'] # four 'h' in which, witch, and watch |
| 684 | 4 |
| 685 | |
| 686 | ''' |
| 687 | # The regular dict.update() operation makes no sense here because the |
| 688 | # replace behavior results in some of the original untouched counts |
| 689 | # being mixed-in with all of the other counts for a mismash that |
| 690 | # doesn't have a straight-forward interpretation in most counting |
| 691 | # contexts. Instead, we implement straight-addition. Both the inputs |
| 692 | # and outputs are allowed to contain zero and negative counts. |
| 693 | |
| 694 | if iterable is not None: |
| 695 | if isinstance(iterable, _collections_abc.Mapping): |
| 696 | if self: |
| 697 | self_get = self.get |
| 698 | for elem, count in iterable.items(): |
| 699 | self[elem] = count + self_get(elem, 0) |
| 700 | else: |
| 701 | # fast path when counter is empty |
| 702 | super().update(iterable) |
| 703 | else: |
| 704 | _count_elements(self, iterable) |
| 705 | if kwds: |
| 706 | self.update(kwds) |
| 707 | |
| 708 | def subtract(self, iterable=None, /, **kwds): |
| 709 | '''Like dict.update() but subtracts counts instead of replacing them. |