Counter class
# class collections.Counter([iterable-or-mapping])# A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.>>> # Tally occurrences of words in a list>>> cnt = Counter()>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:... cnt[word] += 1>>> cntCounter({'blue': 3, 'red': 2, 'green': 1})>>> # Find the ten most common words in Hamlet>>> import re>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())>>> Counter(words).most_common(10)[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] sum(c.values()) # total of all countsc.clear() # reset all countslist(c) # list unique elementsset(c) # convert to a setdict(c) # convert to a regular dictionaryc.items() # convert to a list of (elem, cnt) pairsCounter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairsc.most_common()[:-n-1:-1] # n least common elementsc += Counter() # remove zero and negative counts# most_common([n])# Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.