The Collections Module in Python is different than the other built-in modules. This module contains some different types of containers which is used to store different types of objects.
The Python collection module is defined as a container that is used to store collections of data, for example - list, dict, set, and tuple, etc. It was introduced to improve the functionalities of the built-in collection containers. Python collection module was first introduced in its 2.4 release.
Some common and widely used collection modules are as follows:
The Counters is a part of the Dictionary and is used to count of number of elements in pairs. The dictionary is an unordered, mutable, and indexed collection where each key is unique and maps to the associated value, but since Python 3.7, the insertion in the dictionary is ordered.
We have to import the ordereddict module by using the following command:
from collections import OrderedDict
It has the following syntax:
Let us take an example to demonstrate the Counter collection module in Python.
Output:
This is a Dictionary: w 11 x 12 y 13 z 14 This is an Ordered Dict: a 1 b 2 c 3 d 4
Let us take an example to demponstrate how to delete and reinsert a key using Python collection module.
Output:
Before Deleting w 100 x 200 y 300 z 400 After re-inserting x 200 y 300 z 400 w 100
The DefaultDict consists of default values assigned to a key that does not exist, and because of this, it does not raise any error.
It has the following syntax:
We can initialize the default dictionary by using the DefaultDict() function by passing data types as arguments.
Let us take an example to demonstrate the DefaultDict collection module in Python.
Output:
defaultdict(<class 'int'>, {1: 2, 4: 1, 2: 3, 3: 1, 5: 1, 6: 1})The ChainMap collects and accumulates multiple dictionaries into a single unit and then generates a list of dictionaries.
We can import the ChainMap by the following code:
It has the following syntax:
Let us take an example to illustrate the ChainMap collection module in Python.
Output:
ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600})We can also use the key name to access the value from ChainMap.keys() and values() methods can also be used to access.
Output:
100
ValuesView(ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600}))
KeysView(ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600}))
We can use the new_child() method to add a new dictionary at the beginning of the ChainMap.
Output:
The contents of the ChainMap are:
ChainMap({'a': 123, 'b': 456}, {'b': 789, 'c': 111})
Showing new ChainMap :
ChainMap({'f': 1213}, {'a': 123, 'b': 456}, {'b': 789, 'c': 111})
A tuple is an ordered, immutable collection of elements, which means that once created, its elements cannot be changed. A NamedTuple is similar to a tuple, the only difference being that it consists of named fields, which makes the data easier to read, interpret, and access.
We can import the NamedTuple with the following code:
from collections import namedtuple
It has the following syntax:
Let us take an example to demonstrate the NamedTuple collection module in Python.
Output:
The Employee age using index is: 23 The Employee ID number using field name is: 280202 The Employee name is: Abhay
Deque stands for Doubly Ended Queue. It is a data structure in the collections which is used to perform append and pop operations on both ends of the data structure.
Deque word is often pronounced as the word "Deck". The time complexity for the pop and append operations is O(1), whereas for the list it is O(n).
The Syntax for the deque data structure is:
Let us take an example to demonstrate the deque collection module in Python.
Output:
deque(['name', 'company', 'empid'])
Using the deque data structure, we add and insert the elements in the deque from both ends. We use the append() method to insert the element from the right and the appendleft() method to insert from the left.
Let us take an example to demonstrate how to insert element in a deque using append() function.
Output:
The deque after appending at right is : deque([123, 456, 789, 2025]) The deque after appending at left is : deque([100, 123, 456, 789, 2025])
We added the elements on the left and right sides using the append() method. Similarly, we can also remove the elements from the deque using the pop() method. We use the pop() method to remove the element from the deque from the right end and popleft() to remove from the left end.
Let us take an example to demonstrate how to remove elements from a deque using the pop function in Python.
Output:
The deque after deleting from right is : deque([2016, 2017, 2018, 2019]) The deque after deleting from left is : deque([2017, 2018, 2019])
UserDict behaves as a container that is wrapped around the dictionary objects. It is used for creating a dictionary with extra features, functions, etc.
It has the following syntax:
Let us take an example to demonstrate the UserDict collection module in Python.
Output:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[13], line 21
19 # Create an instance of MyDict
20 d = Dict({'a': 1, 'b': 2, 'c': 3})
---> 21 d.pop(1)
Cell In[13], line 13
12 def pop(self, s=None):
---> 13 raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
We studied that UserDict behaves a wrapper for dictionary objects, similarly, the UserList acts as a container that is wrapped around the list objects. It is used for creating a string with extra features, functions, etc.
It has the following syntax:
Let us take an example to demonstrate the UserList collection module in Python.
Output:
Original List
After Insertion
[100, 200, 300, 400, 500]
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[6], line 24
22 print(L)
23 # Attempt to remove an item (will raise error)
---> 24 L.remove()
Cell In[6], line 9
8 def remove(self, s=None):
----> 9 raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Just UserList behaves as a container that is wrapped around the list objects. The UserString acts as a container that is wrapped around the string objects. It is used for creating a string with extra features, functions, etc.
It has the following syntax:
Let us take an example to demonstrate the UserString collection module in Python.
Output:
Original String: TpointTech String After Appending: TpointTechT String after Removing: TointTechT
In this tutorial, we learnt about Python Collections. The Collections Module in Python is different than the other built-in modules. This module contains some different types of containers which is used to store different types of objects. We learnt about various collection modules like Counters, Default Dictionary, ChainMap, NamedTuple, Deque, UserDict, UserList, and UserString
We request you to subscribe our newsletter for upcoming updates.