Collections is a built-in module in Python, and it is a type of container that contains different modules like Counter, deque, UserDict, UserList etc. Some built-in containers are List, Tuple, Dictionary.
Syntaximport collections from Module_nameCounter
Counter is a function in the collections module. It is a subclass of the dictionary object and counts the number of elements, returning them in the form of an unordered dictionary. Here, the key specifies the element of the sequence, and the value represents the number of occurrences of that element in the sequence.
Syntaxfrom collections import Counter dict_var = Counter(sequence) #---------or-------------- import collections var_dict = collections.Counter(sequence)Example
import collections sequence = ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'] var_dict = collections.Counter(sequence) print(var_dict)Output
Counter({'a': 4, 'b': 4})Example with from
from collections import Counter sequence = ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'] var_dict = Counter(sequence) print(var_dict)Output
Counter({'a': 4, 'b': 4})Accessing the keys and values of dictionary
We can access the keys and values of the unordered dictionary.
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'])Output
Keys: dict_keys(['a', 'b']) values: 4elements() function
elements() function returns a 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("Elements are:", list(var_dict.elements()))Output
Elements are: ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b']