Instagram
youtube
Facebook
Twitter

Python Collections

In python, the collection is a module that provides multiple types of containers. These containers are used to store various types of data. It was introduced to improve and scale the functionalities of the python built-in containers like - lists, tuples, dictionaries, etc. 

In this tutorial, we have covered some popular python collection modules with examples.

namedtuple()

A named tuple () is the function of the python collection module. It is used to return tuple-like objects with their field names.

Example:

from collections import namedtuple
student = namedtuple('student',['ID', 'number'])
student1 = student("g4j56", '101010')
print(student1)
print(student1.ID)
print(student1.number)

Output:

student(ID='g4j56', number='101010')
g4j56
101010

Deque

In python collections, the deque is a queue with two ends. It is an optimized list to perform insertion and deletion. Deque is correctly pronounced as ‘deck’.

Example:

from collections import deque
student = deque([1,2,3,4,5])
student.appendleft("jason")
print(student)
student.append("rahul")
print(student)

Output:

deque(['jason', 1, 2, 3, 4, 5])
deque(['jason', 1, 2, 3, 4, 5, 'rahul'])

ChainMap

ChainMap is a class in python collection module. It is used to create a single view of multiple dictionaries together as a list of dictionaries.

Example:

from collections import ChainMap
a = {'roll_1': "akshat", 'roll_2': "Bhavesh"}
b = {'roll_3': "Chirag", 'roll_4': "Dhanush"}
c = {'roll_5': "Nihal", 'roll_6': "Rohit"}
ans = ChainMap(a,b,c)
print(ans)

Output:

ChainMap({'roll_1': 'akshat', 'roll_2': 'Bhavesh'}, {'roll_3': 'Chirag', 'roll_4': 'Dhanush'}, {'roll_5': 'Nihal', 'roll_6': 'Rohit'})

Counter

In the python collections module Counter is a dictionary subclass. It is used for counting hashable objects.

Example:

from collections import Counter
a = Counter("codersdaily")
print(a)

Output:

Counter({'d': 2, 'c': 1, 'o': 1, 'e': 1, 'r': 1, 's': 1, 'a': 1, 'i': 1, 'l': 1, 'y': 1})

Ordereddict

OrderedDict is a function of python collections module. It is mostly similar to python's normal dictionaries. We can call them subclass of python dictionaries. It remembers the order in which the entries were inserted.

Example:

from collections import OrderedDict
a = OrderedDict()
a['A'] = 1
a['C'] = 2
a['D'] = 3
a['B'] = 4

print(a)

Output:

OrderedDict([('A', 1), ('C', 2), ('D', 3), ('B', 4)])

Defaultdict

Defaultdict is a subclass of dictionaries in the python collection module. It is similar to python's normal dictionaries but it calls a factory function to provide missing values.

Example:

from collections import defaultdict      
number = defaultdict(int)      
number['one'] = 1      
number['two'] = 2   
number['three']
print(number)  

Output:

defaultdict(<class 'str'>, {'one': 'hii', 'two': 'my', 'three': 0})