Python Collections Module
Python Collections Module
The collection Module in Python provides different types of containers. A Container is an object
that is used to store different objects and provide a way to access the contained objects and
iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article,
we will discuss the different containers provided by the collections module.
Table of Content:
Counters
OrderedDict
DefaultDict
ChainMap
NamedTuple
DeQue
UserDict
UserList
UserString
Counters
A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an
iterable in the form of an unordered dictionary where the key represents the element in the
iterable and value represents the count of that element in the iterable.
Syntax:
class collections.Counter([iterable-or-mapping])
The counter object can be initialized using the counter() function and this function can be called
in one of the following ways:
Example:
# with dictionary
print(Counter({'A':3, 'B':5, 'C':2}))
Output:
OrderedDict
An OrderedDict is also a sub-class of dictionary but unlike dictionary, it remembers the order in
which the keys were inserted.
Syntax:
class collections.OrderDict()
Example:
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
Output:
This is a Dict:
a 1
b 2
c 3
d 4
a 1
b 2
c 3
d 4
While deleting and re-inserting the same key will push the key to the last to maintain the order of
insertion of the key.
Example:
# of OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
print(key, value)
# deleting element
od.pop('a')
od['a'] = 1
print('\nAfter re-inserting')
print(key, value)
Output:
Before Deleting
a 1
b 2
c 3
d 4
After re-inserting
b 2
c 3
d 4
a 1
DefaultDict
A DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the
key that does not exist and never raises a KeyError.
Syntax:
class collections.defaultdict(default_factory)
default_factory is a function that provides the default value for the dictionary created. If this
parameter is absent then the KeyError is raised.
DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an
argument.
Example:
# defaultdict
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
for i in L:
# so there is no need to
d[i] += 1
print(d)
Output:
Example 2:
# defaultdict
d = defaultdict(list)
for i in range(5):
d[i].append(i)
print(d)
Output:
ChainMap
A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.
Syntax:
Example:
# ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
print(c)
Output:
Values from ChainMap can be accessed using the key name. They can also be accessed by using
the keys() and values() method.
Example:
# ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
print(c['a'])
# Accessing values using values()
# method
print(c.values())
# method
print(c.keys())
Output:
1
ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
A new dictionary can be added by using the new_child() method. The newly added dictionary is
added at the beginning of the ChainMap.
Example:
# new_child()
import collections
# initializing dictionaries
dic3 = { 'f' : 5 }
# initializing ChainMap
# printing chainMap
print ("All the ChainMap contents are : ")
print (chain)
chain1 = chain.new_child(dic3)
# printing chainMap
print (chain1)
Output:
NamedTuple
A NamedTuple returns a tuple object with names for each position which the ordinary tuples
lack. For example, consider a tuple names student where the first element represents fname,
second represents lname and the third element represents the DOB. Suppose for calling fname
instead of remembering the index position you can actually call the element by using the fname
argument, then it will be really easy for accessing tuples element. This functionality is provided
by the NamedTuple.
Syntax:
Example:
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
print (S[1])
print (S.name)
Output:
Conversion Operations
1. _make(): This function is used to return a namedtuple() from the iterable passed as argument.
2. _asdict(): This function returns the OrdereDict() as constructed from the mapped values of
namedtuple().
Example:
# _make(), _asdict()
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# initializing iterable
# initializing dict
print (Student._make(li))
print (S._asdict())
Output:
Deque
Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from
both sides of the container. It provides O(1) time complexity for append and pop operations as
compared to list with O(n) time complexity.
Syntax:
class collections.deque(list)
Example:
# Python code to demonstrate deque
# Declaring deque
queue = deque(['name','age','DOB'])
print(queue)
Output:
Inserting Elements
Elements in deque can be inserted from both ends. To insert the elements from right append()
method is used and to insert the elements from the left appendleft() method is used.
Example:
# append(), appendleft()
# initializing deque
de = deque([1,2,3])
de.append(4)
# printing modified deque
print (de)
de.appendleft(6)
print (de)
Output:
Removing Elements
Elements can also be removed from the deque from both the ends. To remove elements from
right use pop() method and to remove elements from the left use popleft() method.
Example:
# initializing deque
de = deque([6, 1, 2, 3, 4])
print (de)
de.popleft()
print (de)
Output:
UserDict
UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This
container is used when someone wants to create their own dictionary with some modified or new
functionality.
Syntax:
class collections.UserDict([initialdata])
Example:
# userdict
from collections import UserDict
class MyDict(UserDict):
# from dictionary
def __del__(self):
# dictionary
# from Dictionary
# Driver's code
d = MyDict({'a':1,
'b': 2,
'c': 3})
d.pop(1)
Output:
UserList
UserList is a list like container that acts as a wrapper around the list objects. This is useful when
someone wants to create their own list with some modified or additional functionality.
Syntax:
class collections.UserList([list])
Example:
# userlist
class MyList(UserList):
# from List
# List
# Driver's code
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
L.remove()
Output:
Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in <module>
L.remove()
File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
UserString
UserString is a string like container and just like UserDict and UserList it acts as a wrapper around
string objects. It is used when someone wants to create their own strings with some modified or
additional functionality.
Syntax:
class collections.UserString(seq)
Example:
# userstring
class Mystring(UserString):
# Function to append to
# string
self.data += s
# string
# Driver's code
s1 = Mystring("Geeks")
# Appending to string
s1.append("s")
s1.remove("e")
Output: