The Collections Module in Python stands apart from other standard modules. This module includes various container types designed for storing diverse object types.
The Python collections module is characterized as a container designed to hold groups of data, such as lists, dictionaries, sets, and tuples, among others. Its purpose is to enhance the capabilities of the standard collection containers. The collections module was first introduced in Python version 2.4.
Some common and widely used collection modules are as follows:
- Counters
- Default Dictionary
- ChainMap
- NamedTuple
- Deque
- UserDict
- UserList
- UserString
Counters
The Counters component is an extension of the Dictionary, utilized for tallying the number of elements in pairs. A dictionary functions as an unordered, mutable, and indexed collection in which each key is distinct and corresponds to a specific value. However, starting from Python 3.7, the order of insertion within the dictionary is preserved.
To utilize the ordereddict module, we must import it with the following command:
from collections import OrderedDict
Python Counter Syntax
It has the following syntax:
class collections.OrderDict()
Python Counter Example
Let's consider an example to illustrate the Counter collection module in Python.
Example
#importing the counter from the collections
from collections import OrderedDict
print("This is a Dictionary:\n")
d = {}
d['w'] = 11
d['x'] = 12
d['y'] = 13
d['z'] = 14
for key, value in d.items():
print(key, value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
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
Example of deleting and reinserting a key
Let’s consider an example to illustrate how to remove and then reinsert a key utilizing the Python collection module.
Example
#importing the counter from the collections
from collections import OrderedDict
odict = OrderedDict()
odict['w'] = 100
odict['x'] = 200
odict['y'] = 300
odict['z'] = 400
print('Before Deleting')
for key, value in odict.items():
print(key, value)
# deleting the element
odict.pop('w')
# Re-inserting the same element
odict['w'] = 100
print('\nAfter re-inserting')
for key, value in odict.items():
print(key, value)
Output:
Before Deleting
w 100
x 200
y 300
z 400
After re-inserting
x 200
y 300
z 400
w 100
DefaultDict
The DefaultDict is characterized by the provision of default values for keys that are absent, which allows it to avoid raising any errors.
Python DefaultDictSyntax
It has the following syntax:
class collections.defaultdict(default_factory)
The default dictionary can be created using the DefaultDict function, where data types are supplied as arguments.
Python DefaultDict Example
Let's consider an example to illustrate the DefaultDict collection module in Python.
Example
#importing the counter from the collections
from collections import defaultdict
# here we are creating a default dictionary with the default value of 0 (int)
dict = defaultdict(int)
A = [1,4,2,3,1,2,5,6,2]
# Counting occurrences of each element in the list
for i in A:
dict[i] += 1
print(dict)
Output:
defaultdict(<class 'int'>, {1: 2, 4: 1, 2: 3, 3: 1, 5: 1, 6: 1})
ChainMap
The ChainMap gathers and combines several dictionaries into one cohesive entity and subsequently produces a collection of dictionaries.
We can import the ChainMap by the following code:
from collections import ChainMap
Python ChainMap Syntax
It has the following syntax:
class collections.ChainMap(dict1, dict2)
Python ChainMap Example
To demonstrate the ChainMap collection module in Python, let us consider an example.
Example
#importing the counter from the collections
from collections import ChainMap
dict1 = {'a': 100, 'b': 200}
dict2 = {'c': 300, 'd': 400}
dict3 = {'e': 500, 'f': 600}
#merging the multiple dictionaries
c = ChainMap(dict1, dict2, dict3)
# printing the output
print(c)
Output:
ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600})
The value can also be retrieved using the key name through the ChainMap.keys method, while the values method can similarly be employed for access.
Example
# Importing namedtuple from the collections module
from collections import ChainMap
dict1 = {'a': 100, 'b': 200}
dict2 = {'c': 300, 'd': 400}
dict3 = {'e': 500, 'f': 600}
# here we are creating the chainmap
cm = ChainMap(dict1, dict2 , dict3)
# Accessing Values using key name
print(cm['a'])
# Accessing values using values() method
print(cm.values())
# Accessing keys using keys() method
print(cm.keys())
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}))
Adding a new dictionary
The new_child function allows us to insert a new dictionary at the start of the ChainMap.
Example
#importing the collections module
import collections
# creating the dictionaries
dict1 = { 'a' : 123, 'b' : 456 }
dict2 = { 'b' : 789, 'c' : 111 }
dict3 = { 'f' : 1213 }
# initializing ChainMap
chain = collections.ChainMap(dict1, dict2)
# printing chainMap
print ("The contents of the ChainMap are: ")
print (chain)
# here we are using the new_child() to add new dictionary
n_chain = chain.new_child(dict3)
# printing chainMap
print ("Showing new ChainMap : ")
print (n_chain)
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})
NamedTuple
A tuple is a collection of elements that is both ordered and immutable, indicating that its elements cannot be altered once it has been established. A NamedTuple resembles a tuple, with the sole distinction being that it contains named fields, enhancing the clarity, interpretation, and accessibility of the data.
The NamedTuple can be imported using the subsequent code:
from collections import namedtuple
Python NamedTuple Syntax
It has the following syntax:
class collections.namedtuple(typename, field_names)
Python NamedTuple Example
Let's consider an example to illustrate the NamedTuple collection module in Python.
Example
# Importing namedtuple from the collections module
from collections import namedtuple
# Creating namedtuple()
Employee = namedtuple('Employee', ['name', 'age', 'ID_number'])
# Creating an instance of an Employee
E = Employee('Abhay', '23', '280202')
# Access using index
print("The Employee age using index is: ", end="")
print(E[1])
# Access using field name
print("The Employee ID number using field name is: ", end="")
print(E.ID_number)
print("The Employee name is: ", end="")
print(E.name)
Output:
The Employee age using index is: 23
The Employee ID number using field name is: 280202
The Employee name is: Abhay
Deque
Deque is an abbreviation for Doubly Ended Queue. This data structure is part of collections and allows for the execution of append and pop operations at both ends of the structure.
The term "Deque" is frequently articulated like the word "Deck." The time complexity for the operations of pop and append is O(1), in contrast to the list, which has a time complexity of O(n).
Python Deque Syntax:
The Syntax for the deque data structure is:
class collections.deque(list)
Python Deque Example
To illustrate the usage of the deque collection module in Python, let’s consider an example.
Example
#importing the deque data structure from collection
from collections import deque
# Declaring deque
q1 = deque(['name','company','empid'])
print(q1)
Output:
deque(['name', 'company', 'empid'])
Inserting Elements
By utilizing the deque data structure, we can add and insert elements at both ends of the deque. The append method is employed to insert elements on the right side, while the appendleft method is used for insertion on the left side.
Python Example for Inserting Elements
Consider an example to illustrate the process of adding an element to a deque utilizing the append method.
Example
#importing the deque data structure from collection
from collections import deque
# Initializing deque with initial values
de = deque([123, 456, 789])
# here we appending a number 2025 to the right end of deque
de.append(2025)
#printing the deque after the number to the right end
print("The deque after appending at right is :")
print(de)
#now we are appending the number to the left end of the deque
de.appendleft(100)
#printing the deque after the number to the left
print("The deque after appending at left is :")
print(de)
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])
Removing Elements
Elements were incorporated on both the left and right sides utilizing the append method. In a similar fashion, elements can be eliminated from the deque through the pop method. The pop method is employed to remove an element from the right side of the deque, while popleft is used for removing an element from the left side.
Python Example to Remove Elements using Deque
Let’s consider an example to illustrate the process of eliminating elements from a deque utilizing the pop function in Python.
Example
#importing the deque data structure from collection
from collections import deque
# Initialize deque with initial values
de = deque([2016, 2017, 2018, 2019, 2020])
# here we deleting a number from the right end of deque
de.pop()
#printing the deque after deleting the number from the right end
print("The deque after deleting from right is :")
print(de)
#now we are deleting the number from the left end of the deque
de.popleft()
#printing the deque after deleting the number from the left
print("The deque after deleting from left is :")
print(de)
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
UserDict functions as a wrapper around dictionary objects, serving as a container. It is utilized to construct a dictionary that includes additional features, functionalities, and more.
Python UserDict Syntax:
It has the following syntax:
class collections.UserDict([initialdata])
Python UserDict Example
To illustrate the UserDict collection module in Python, let's consider an example.
Example
#importing the UserDict from collection
from collections import UserDict
# we are creating a dictionary where deletion is prohibited
class Dict(UserDict):
# It stops using 'del' on dictionary
def __del__(self):
raise RuntimeError("Deletion not allowed")
# It prevents using pop() on dictionary
def pop(self, s=None):
raise RuntimeError("Deletion not allowed")
# It prevents using popitem() on dictionary
def popitem(self, s=None):
raise RuntimeError("Deletion not allowed")
# Create an instance of MyDict
d = Dict({'a': 100, 'b': 200, 'c': 300})
d.pop(1)
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
UserList
Our examination revealed that UserDict functions as a wrapper for dictionary instances, while UserList serves as a container that encapsulates list objects. It is utilized for generating a string with additional functionalities, features, and so forth.
Python UserList Syntax:
It has the following syntax:
class collections.UserList([list])
Python UserList Example
Let’s consider an example to illustrate the UserList collection module found in Python.
Example
#importing the UserList from collection
from collections import UserList
# we are creating a list and deletion of the object is prohibited
class List(UserList):
# Prevents using remove() on list
def remove(self, s=None):
raise RuntimeError("Deletion not allowed")
# Prevents using pop() on list
def pop(self, s=None):
raise RuntimeError("Deletion not allowed")
# We are Creating an instance of List
L = List([100, 200, 300, 400])
print("Original List")
#here we are Appending 500 to the list
L.append(500)
print("After Insertion")
print(L)
# Attempt to remove an item (will raise error)
L.remove()
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
UserString
The UserList functions as a wrapper that encapsulates list objects. Similarly, the UserString serves as a wrapper around string objects. It is utilized for generating a string that includes additional functionalities, features, and so forth.
Python UserString Syntax
It has the following syntax:
class collections.UserString(sequence)
Python UserString Example
We will use an example to illustrate the UserString collection module in Python.
Example
#importing the UserString from collection
from collections import UserString
# Creating a Mutable String
class string(UserString):
# defining a function to append to string
def append(self, s):
self.data += s
# defining a function to remove from string
def remove(self, s):
self.data = self.data.replace(s, "")
# inputting the string
str = string("Example")
print("Original String:", str.data)
# appending the letter to the string
str.append("T")
print("String After Appending:", str.data)
# deleting the letter from the string
str.remove("p")
print("String after Removing:", str.data)
Output:
Original String: C# Tutorial
String After Appending: C# TutorialTechT
String after Removing: TointTechT
Conclusion
In this tutorial, we explored Python Collections. The Collections Module in Python stands apart from other built-in modules. This module comprises various types of containers designed for storing diverse object types. We examined several collection types, including Counters, Default Dictionary, ChainMap, NamedTuple, Deque, UserDict, UserList, and UserString.
Python Collections FAQs
1. What is the use of the collections in Python?
The Collections Module in Python distinguishes itself from other built-in modules. This module comprises various types of containers designed for the storage of diverse objects. Among the collections are Counter, DefaultDict, ChainMap, NamedTuple, and more.
2. Are collections built in Python, or do we have to install them separately?
Indeed, the collections module is integrated within Python, and we access it by using the command import collections. There is no need for a separate installation.
3. What is the use of defaultdict?
The DefaultDict includes predefined values for keys that are absent, which prevents it from generating any errors.
Syntax: class collections.defaultdict(default_factory)
The default dictionary can be created by utilizing the DefaultDict function, providing data types as parameters.
4. How is ChainMap useful?
The ChainMap gathers and consolidates several dictionaries into one cohesive entity, subsequently producing a list of dictionaries.
We can import the ChainMap by the following code:
from collections import ChainMap
5. What is the difference between NamedTuple and the Tuple?
A tuple is a collection of elements that is both ordered and immutable, indicating that its elements cannot be altered after it has been created.
A NamedTuple resembles a standard tuple, with the distinction that it is composed of named attributes, enhancing the clarity, understanding, and accessibility of the data.
The NamedTuple can be imported using the following code:
from collections import namedtuple
6. Why use deque instead of a list?
Deque is short for Doubly Ended Queue. This data structure is part of the collections framework and allows for appending and removing elements from both ends. The advantage of using a deque lies in its time complexity for pop and append operations, which is O(1), in contrast to O(n) for a list.
7. What is UserDict and when is it used?
UserDict acts as a wrapper around dictionary objects, functioning as a container. It is utilized for developing a dictionary that includes additional features, functions, and more.
8. Is NamedTuple mutable?
Similar to a Tuple, a NamedTuple is also characterized by its immutability, indicating that once it has been instantiated, its values remain unalterable.
9. What is Counter used for in Collections?
The Counters function is a component of the Dictionary, utilized to tally the number of elements within pairs. A dictionary serves as an unordered, mutable, and indexed collection in which each key is distinct and corresponds to its related value. However, starting from Python 3.7, the order of insertion in the dictionary is preserved.
10. Can we convert defaultdict to a normal dictionary?
Indeed, transforming a defaultdict into a standard dictionary is straightforward by utilizing dict(defaultdict_instance).