Python
Flask vs Django: What's the Difference Between Flask & Django?
In this tutorial of difference between Flask vs Django, we will discuss the key differences...
Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class.
The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.
Here, are major reasons for using Python 3 Counter:
In this Python tutorial you will learn:
Python Counter takes in input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element.
Syntax:
Counter(list)
Consider you have a following list :
list1 = ['x','y','z','x','x','x','y', 'z']
The list has elements x , y and z.When you use Counter on this list , it will count how many times x , y and z is present. The output if counter is used on list1 should be something like :
Counter({'x': 4, 'y': 2, 'z': 2})
So we have the count of x as 4, y as 2 and z as 2.
To make use of Counter we need to import it first as shown in the below given example:
from collections import Counter
Here is a simple example , that shows the working of Counter module.
from collections import Counter list1 = ['x','y','z','x','x','x','y', 'z'] print(Counter(list1))
Output:
Counter({'x': 4, 'y': 2, 'z': 2})
In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.
In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.
Example:
from collections import Counter my_str = "Welcome to gtupapers Tutorials!" print(Counter(my_str))
Output:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
A list is an iterable object that has its elements inside square brackets.
The elements in the list when given to the Counter will be converted to a hashtable objects wherein the elements will become keys and the values will be the count of the elements from the list given.
For example ['x','y','z','x','x','x','y','z']. Once you give the list the Counter, it will give you the count of each element in the list.
from collections import Counter list1 = ['x','y','z','x','x','x','y','z'] print(Counter(list1))
Output:
Counter({'x': 4, 'y': 2, 'z': 2})
A dictionary has elements as key/value pair, and they are written inside curly brackets.
Once the dictionary is given to the Counter, it will be converted to a hashtable objects wherein the elements will become keys, and the values will be the count of the elements from the dictionary given.
For example : {'x': 4, 'y': 2, 'z': 2, 'z': 2}. The Counter function will try to find the count of each of the key in the given dictionary.
from collections import Counter
dict1 = {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))
Output:
Counter({'x': 4, 'y': 2, 'z': 2})
Tuple is a collection of objects separated by commas inside round brackets. Counter will give you the count of each of the elements in the tuple given.
Once the tuple is given to the Counter, it will be converted to a hashtable object wherein the elements will become keys and the values will be the count of the elements from the tuple given.
from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))
Output:
Counter({'x': 4, 'y': 2, 'z': 2})
A Counter can be initialized by passing string value, list, dictionary, or tuple as shown below:
from collections import Counter
print(Counter("Welcome to gtupapers Tutorials!")) #using string
print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple
You can also initialize a empty Counter as shown below:
from collections import Counter _count = Counter()
You can add values to the Counter by using update() method.
_count.update('Welcome to gtupapers Tutorials!')
The final code is :
from collections import Counter
_count = Counter()
_count.update('Welcome to gtupapers Tutorials!')
print(_count)
The output is:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
To get the values from the Counter, you can do as follows:
from collections import Counter
_count = Counter()
_count.update('Welcome to gtupapers Tutorials!')
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Guru':
print('%s : %d' % (char, _count[char]))
Output:
u : 3 G : 1 u : 3 r : 2 u : 3
To delete an element from Counter you can make use of del , as shown in the example below:
Example:
from collections import Counter
dict1 = {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))
Output:
Counter({'y': 2, 'z': 2})
Arithmetic operation like addition, subtraction, intersection and union can be done on a Counter as shown in the example below:
Example:
from collections import Counter
counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })
#Addition
counter3 = counter1 + counter2 # only the values that are positive will be returned.
print(counter3)
#Subtraction
counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output
print(counter4)
#Intersection
counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2
print(counter5)
#Union
counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2
print(counter6)
Output:
Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})
There are some important methods available with Counter, here is the list of same:
from collections import Counter
counter1 = Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})
_elements = counter1.elements() # will give you all elements with positive value and count>0
for a in _elements:
print(a)
Output:
x x x x x y y
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next.
print(common_element)
common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element.
print(common_element1)
Output:
[('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.subtract(counter2)
print(counter1)
Output:
Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)
Output:
Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})
You can re-assign counts of Counter as shown below:
Consider you have a dictionary as : {'x': 5, 'y': 12, 'z': -2, 'x1':0}
You can change the count of the element as shown below:
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter1['y'] = 20
print(counter1)
Output: After executing you will see that y count is changed from 12 to 20
Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})
To get the count of an element using Counter you can do as follows:
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y']) # this will give you the count of element 'y'
Output:
12
To set the count of the element you can do as follows:
from collections import Counter
counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y'])
counter1['y'] = 20
counter1['y1'] = 10
print(counter1)
Output:
12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})
In this tutorial of difference between Flask vs Django, we will discuss the key differences...
What is Python Range? Python range() is a built-in function available with Python from...
What are Conditional Statements in Python? Conditional Statement in Python perform different...
Before we learn Django, let's understand: What is a Web Framework? A web framework is a code...
What is JSON? JSON is a standard format for data exchange, which is inspired by JavaScript....
Python List data-type helps you to store items of different data types in an ordered sequence. The...