collections is a built-in module in python and it is type of container that contains different module like Counter,deque,UserDict,UserList etc and some built-in container are List,tuple,Dictonary.
import collections from Module_name
Counter is function comes in the collections module and it is subclass of dictionary object and the use of Counter function count the number of element and return in the form of unordered Dictonary,here the key specifies the element of sequence and value represents the number of element of that sequence.
from collections import Counter dict_var=Counter(sequence) #---------or-------------- import collections var_dict=collections.Counter(sequence)
import collections sequence=['a','b','a','b','a','b','a','b'] var_dict=collections.Counter(sequence) print(var_dict)
Counter({'a': 4, 'b': 4})
from collections import Counter sequence=['a','b','a','b','a','b','a','b'] var_dict=Counter(sequence) print(var_dict)
Counter({'a': 4, 'b': 4})
We can access the keys and values of the unordered dictonary.
from collections import Counter sequence=['a','b','a','b','a','b','a','b'] var_dict=Counter(sequence) print("Keys:",var_dict.keys()) print("values:",var_dict['a'])
Keys: dict_keys(['a', 'b']) values: 4
elements() function return the list which contains list of all the elements in the Counter object.
from collections import Counter sequence=['a','b','a','b','a','b','a','b'] var_dict=Counter(sequence) print("Element are:",list(var_dict.elements()))
Element are: ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b']