Linux

Python Collections

Up to this level of Python, you have learned data structure of Python. The Python collections 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.
Python Collections Counter to check frequency
Counter 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 Collections Counter use list
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() method.
Python Counter using update method
Counter 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 string's letter Comparing using counter
Comparing using string counter
Click to view code
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.
Frequency calculation using Python counter
Frequency calculation using counter
Click to view code
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().
Syntax
most_common(number)
argument number means how many top letter you wants to prints.

See next example.
Calculate top frequency letter using Python most_common()
Counter most_common
Click to view code
In Python collection Counter you can apply sets operation like addition, subtraction, Union and intersection.
As shown below.
addition, subtraction, Union and intersection using python counter
Counter set operation
Click to view code
I hope you have enjoyed the Python collection Counter, In next chapter you will learn collection Deque.




admin