Python Collection Module

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:

  • Counters
  • Default Dictionary
  • ChainMap
  • NamedTuple
  • Deque
  • UserDict
  • UserList
  • UserString

Counters

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

Python Counter Syntax

It has the following syntax:

class collections.OrderDict()  

Python Counter Example

Let us take an example to demonstrate 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 us take an example to demponstrate how to delete and reinsert a key using 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 consists of default values assigned to a key that does not exist, and because of this, it does not raise any error.

Python DefaultDictSyntax

It has the following syntax:

class collections.defaultdict(default_factory)  

We can initialize the default dictionary by using the DefaultDict() function by passing data types as arguments.

Python DefaultDict Example

Let us take an example to demonstrate 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 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:

from collections import ChainMap  

Python ChainMap Syntax

It has the following syntax:

class collections.ChainMap(dict1, dict2)  

Python ChainMap Example

Let us take an example to illustrate the ChainMap collection module in Python.

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})

We can also use the key name to access the value from ChainMap.keys() and values() methods can also be used to 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

We can use the new_child() method to add a new dictionary at the beginning 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 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

Python NamedTuple Syntax

It has the following syntax:

class collections.namedtuple(typename, field_names)  

Python NamedTuple Example

Let us take an example to demonstrate 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 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).

Python Deque Syntax:

The Syntax for the deque data structure is:

class collections.deque(list)  

Python Deque Example

Let us take an example to demonstrate the deque collection module in Python.

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

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.

Python Example for Inserting Elements

Let us take an example to demonstrate how to insert element in a deque using append() function.

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

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.

Python Example to Remove Elements using Deque

Let us take an example to demonstrate how to remove elements from a deque using 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 behaves as a container that is wrapped around the dictionary objects. It is used for creating a dictionary with extra features, functions, etc.

Python UserDict Syntax:

It has the following syntax:

class collections.UserDict([initialdata])  

Python UserDict Example

Let us take an example to demonstrate the UserDict collection module in Python.

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

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.

Python UserList Syntax:

It has the following syntax:

class collections.UserList([list])  

Python UserList Example

Let us take an example to demonstrate the UserList collection module 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

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.

Python UserString Syntax

It has the following syntax:

class collections.UserString(sequence)  

Python UserString Example

Let us take an example to demonstrate 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_obj = string("Learn Python App")  
print("Original String:", str_obj.data)  

# appending a character or word to the string  
str_obj.append("!")  
print("String After Appending:", str_obj.data)  

# deleting a specific letter from the string  
# (In this case, removing 'p' from 'App')
str_obj.remove("p")  
print("String after Removing:", str_obj.data)

Output:

Original String: Learn Python App
String After Appending: Learn Python App!
String after Removing: Learn Python A!

Conclusion

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *