Counter
Counter is a sub-class of dict data type. It's used to maintain track of the items in an iterable in the form of an unordered dictionary, with the key representing the element and the value representing the count of that element in the iterable.
Syntax:
c = Counter(mapping/iterable)

You can also try this code with Online Python Compiler
Run Code
Example:
from collections import Counter
c = Counter("aabbccdddeee")
print(c)

You can also try this code with Online Python Compiler
Run CodeOutput:
Counter({'d': 3, 'e': 3, 'a': 2, 'b': 2, 'c': 2})

You can also try this code with Online Python Compiler
Run Code
Example:
from collections import Counter
c = Counter([1,1,2,2,3])
print(c)

You can also try this code with Online Python Compiler
Run CodeOutput:
Counter({1: 2, 2: 2, 3: 1})

You can also try this code with Online Python Compiler
Run Code
Example:
from collections import Counter
c = Counter(a=5,b=9)
print(c)

You can also try this code with Online Python Compiler
Run CodeOutput:
Counter({'b': 9, 'a': 5})

You can also try this code with Online Python Compiler
Run Code
Counter objects support the following methods:
- elements(): it returns an iterator over elements repeating each as many times as its count.
- most_common([x]): it returns a list of the x elements with the highest count.
from collections import Counter
c = Counter([1,1,1,1,2,2,2,2,5,6,5,2,3,3,3,])
print(list(c.elements()))
print(c.most_common(2))

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 1, 1, 1, 2, 2, 2, 2, 2, 5, 5, 6, 3, 3, 3]
[(2, 5), (1, 4)]

You can also try this code with Online Python Compiler
Run Code
You can practice by yourself with the help of online python compiler.
OrderedDict
A dictionary subclass called OrderedDict remembers the order in which keys were initially placed. Items are returned in the order their keys were initially added while iterating over an ordered dictionary. Because an ordered dictionary keeps track of its entry order, it may be used with sorting to produce a sorted dictionary.
If a key is removed and added again, the key is pushed to the last position to maintain the order.
Example:
from collections import OrderedDict
ordDict = {}
ordDict[3]=4
ordDict[1]=2
ordDict[2]=3
ordDict[4]=1
print("Before")
for key in ordDict:
print(key,ordDict[key])
ordDict.pop(3)
ordDict[3]=10
print("After")
for key in ordDict:
print(key,ordDict[key])

You can also try this code with Online Python Compiler
Run Code
Output:
Before
3 4
1 2
2 3
4 1
After
1 2
2 3
4 1
3 10

You can also try this code with Online Python Compiler
Run CodeDefaultdict
It is a subclass of dictionary. It's used to supply default values for keys that don't exist, and it never throws a KeyError.
Example:
from collections import defaultdict
dic = defaultdict(lambda:0)
print(dic[1])

You can also try this code with Online Python Compiler
Run CodeOutput:
0

You can also try this code with Online Python Compiler
Run CodeChainMap
A ChainMap collects many dictionaries into a single unit and delivers a list of dictionaries.
Syntax:
collections.ChainMap(dictionary1, dictionary2)

You can also try this code with Online Python Compiler
Run CodeExample:
import collections
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
c = collections.ChainMap(dic1,dic2)
print(c)
print(c.keys())
print(c.values())

You can also try this code with Online Python Compiler
Run Code
Output:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))

You can also try this code with Online Python Compiler
Run Code
A new dictionary can be added to a chain map using the new_child method. It adds the new dictionary to the beginning of the chain of dictionaries.
import collections
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
c = collections.ChainMap(dic1,dic2)
print(c)
dic3 = {"e":5,"f":6}
c1 = c.new_child(dic3)
print(c1)

You can also try this code with Online Python Compiler
Run Code
Output:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
ChainMap({'e': 5, 'f': 6}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4})

You can also try this code with Online Python Compiler
Run CodeNamedTuple
The NamedTuple returns tuple-like objects with extra functionalities. In this, each position of the tuple can be named as well as indexed.
Syntax:
collections.namedtuple(type_name,fields)

You can also try this code with Online Python Compiler
Run Code
For example, creating a namedtuple .
import collections
person = collections.namedtuple('person',["name","age","country"])

You can also try this code with Online Python Compiler
Run Code
Creating an object of person namedtupe.
p1 = person("Apurv", 20, "India")

You can also try this code with Online Python Compiler
Run Code
Accessing the fields of p1.
print(p1.name)
print(p1.age)
print(p1.country)

You can also try this code with Online Python Compiler
Run Code
Output:
Apurv
20
India

You can also try this code with Online Python Compiler
Run Code
Example:
import collections
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
c = collections.ChainMap(dic1,dic2)
print(c)
print(c.keys())
print(c.values())

You can also try this code with Online Python Compiler
Run Code
Output:
Chain

You can also try this code with Online Python Compiler
Run CodeDeque
A deque, also called a Doubly-ended queue, is a specialized list that can perform append and pop operations from both sides of the list in constant time.
Appending elements to the right in the deque is the same as the normal list. Appending elements and pop elements from the left can be done using deque.appendleft() and deque.popleft() method.
Syntax:
collections.deque(list)

You can also try this code with Online Python Compiler
Run Code
Example:
import collections
l = [1,2,3,4,5]
d = collections.deque(l)
d.popleft()
print(d)
d.appendleft(9)
print(d)

You can also try this code with Online Python Compiler
Run Code
Output:
deque([2, 3, 4, 5])
deque([9, 2, 3, 4, 5])

You can also try this code with Online Python Compiler
Run CodeUserDict
UserDict is a string-like container that works as a wrapper over dict objects, similar to UserList and UserString. It's utilised when someone wants to make their own dict with some tweaks or other features.
Syntax:
collections.UserDict(dict)

You can also try this code with Online Python Compiler
Run Code
Example:
import collections
class CustomDict(collections.UserDict):
def returnValueOfSmallestKey(self):
keys = list(self.data.keys())
return self.data[min(keys)]
List = CustomDict({1:"a",2:"b",3:"c"})
print(List)
print(List.returnValueOfSmallestKey())

You can also try this code with Online Python Compiler
Run Code
Output:
a

You can also try this code with Online Python Compiler
Run CodeUserList
UserList is a string-like container that works as a wrapper over list objects, similar to UserDict and UserString. It's utilised when someone wants to make their own list with some tweaks or other features.
Syntax:
collections.UserList(list)

You can also try this code with Online Python Compiler
Run Code
Example:
import collections
class CustomList(collections.UserList):
def replaceMiddle(self,x):
self.data[len(self.data)//2] = x
List = CustomList([1,2,3,4,5])
print(List)
List.replaceMiddle(9)
print(List)

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 2, 3, 4, 5]
[1, 2, 9, 4, 5]

You can also try this code with Online Python Compiler
Run CodeUserString
UserString is a string-like container that works as a wrapper over string objects, similar to UserDict and UserList. It's utilised when someone wants to make their own strings with some tweaks or other features.
Syntax:
collections.UserString(string)

You can also try this code with Online Python Compiler
Run Code
Example:
import collections
class CustomString(collections.UserString):
def replaceMiddle(self,x):
temp = list(self.data)
temp[len(temp)//2] = x
self.data = ''.join(temp)
string = CustomString("Thisisastring")
print(string)
string.replaceMiddle("x")
print(string)

You can also try this code with Online Python Compiler
Run Code
Output:
Thisisastring
Thisisxstring

You can also try this code with Online Python Compiler
Run Code
Frequently Asked Questions
What is Collections Module in Python?
Collections module in Python provides a large number of specialized containers that have been specially designed to solve specialized problems.
How many containers does the collections module in Python provide?
The collections module provides the following containers: Counter, OrderedDict, DefaultDict, ChainMap, NamedTuple, Deque, Userdict, UserList, UserString.
How to set the default value of defaultdict in Python?
The default value of the defaultdict can be set by defaultdict(lambda:x), where x is the default value.
Conclusion
In this blog, we understood the Collections module and its usage in Python. We also learned about different containers the Collections module provides. Python collections module is a powerful addition to the standard library, offering specialized data structures like named tuples, deques, and defaultdicts. These tools simplify complex data handling, making your code more efficient and readable. By leveraging the collections module, you can enhance your programming capabilities and tackle a variety of tasks with ease.
You can refer to our Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.