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)
| 63 | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 64 | |
| 65 | def update(self, iterable=None, **kwds): |
| 66 | '''Like dict.update() but add counts instead of replacing them. |
| 67 | |
| 68 | Source can be an iterable, a dictionary, or another Counter instance. |
| 69 | |
| 70 | >>> c = Counter('which') |
| 71 | >>> c.update('witch') # add elements from another iterable |
| 72 | >>> d = Counter('watch') |
| 73 | >>> c.update(d) # add elements from another counter |
| 74 | >>> c['h'] # four 'h' in which, witch, and watch |
| 75 | 4 |
| 76 | |
| 77 | ''' |
| 78 | if iterable is not None: |
| 79 | if hasattr(iterable, 'iteritems'): |
| 80 | if self: |
| 81 | self_get = self.get |
| 82 | for elem, count in iterable.iteritems(): |
| 83 | self[elem] = self_get(elem, 0) + count |
| 84 | else: |
| 85 | dict.update(self, iterable) # fast path when counter is empty |
| 86 | else: |
| 87 | self_get = self.get |
| 88 | for elem in iterable: |
| 89 | self[elem] = self_get(elem, 0) + 1 |
| 90 | if kwds: |
| 91 | self.update(kwds) |
| 92 | |
| 93 | def copy(self): |
| 94 | 'Like dict.copy() but returns a Counter instance instead of a dict.' |