Up to this level of Python, you have learned data structure of Python.
module of Python includes implementations of several data structures
that extend those found in other modules. Gradually you will learn the power of Python collections module.
Let us discuss its power one by one.
Python Collections Counter
In simple words, Python Counter is container and tracks the frequency of values.
See the example.
You have seen, how Python counter gives you frequency of letter or word. It return a dictionary or key and value, key represents the
word and value represents its frequency.
Python Counter Example2
The above figure shows three different example of Python Counter
If you pass only one string it will return frequency of letter of string.
You can pass a list of words or letter to Python Counter
If list contains a string then Python Counter
treats it as single word.
Empty or non-empty Python Counter
can be updated by Update()
By seeing above example you can understood that update program can also increase the frequency.
In next example you will see a real problem solved by Counter
Consider you have string and you want to compare it letter frequency with another string. As shown below.
Python collection Counter
does not raise KeyError for unknown items. If a value has not been
seen in the input (as with e in this example), its count is 0.
Consider a another problem of real world to calculate the frequency of letters from text file.
Let us discuss in example.
The above program gives frequency of all letter. However you can choose first five letter of higher frequency.
In order to select top frequency letter you can use most_common()
argument number means how many top letter you wants to prints.
See next example.
you can apply sets operation like addition, subtraction, Union and intersection.
As shown below.
I hope you have enjoyed the Python collection Counter, In next chapter you will learn collection Deque.