What's the difference between a Python dictionary and a Python Counter?


#1

Question

In this exercise, we see the use of the Python Counter data structure to store strings as keys and numbers as values. We would usually use a dictionary to do this. What’s the difference between a dict and a Counter? When should we choose to use a Counter?

Answer

The Counter data structure is much less flexible than the dictionary. It is designed to be high performance for applications specific to tallying. So it is a great choice in the case of this exercise where we want to examine many long strings and tally the number of times we see each unique word. Since we don’t want to do anything more than that, we don’t need the added flexibility of a dictionary. As a result, we get faster access and some other helpful functionality which is helpful for tallying applications. One of the most important of which is

  • most_common ([ n ])
    Returns a list of the n most common elements and their counts from the most common to the least.

So if your application requires only tallying and you want to do this as efficiently as possible, you should consider looking into the Counter collection.