Collections In Python Programming

In this write, we going to learn a collections module in Python programming. This tutorial series will consist of 3 parts.

What is Collections Module?

The collection module is an object used to store different objects and to access and refresh stored objects. For example, tuples, lists, dictionaries can be stored.

This article will consist of approximately 3 parts. In this article, we will see simple terms and important objects.

In the second article, we will cover broader topics and in the last article we will repeat what we have learned.

Counter Object In Collections

It can be used with counter objects, dictionaries, lists, and variables; its main purpose is to calculate and sort the content of the value contained in it.

from collections import Counter

# With List
print(Counter([1 , 2 , 2 , 3 , 3]))
# With Variable
print(Counter(A = 2 , B = 3 , C = 4))
# With Dictionary
print(Counter({"X": 3 , "Y": 2 , "Z": 4}))
Output:
Counter({2: 2, 3: 2, 1: 1})
Counter({'C': 4, 'B': 3, 'A': 2})
Counter({'Z': 4, 'X': 3, 'Y': 2})

Chainmap In Collections

It collects your dictionaries in one unit and returns a dictionary list. In this way, you can combine your large data sets of more than one.

from collections import ChainMap

d1 = {"A": 12}
d2 = {"S": 11}
d3 = {"X": 88}

x = ChainMap(d1 , d2 , d3)

print(x)
print(x["A"])
 # search with using keyname
print(x.values()) # Accesing values using values method
print(x.keys()) # Accessing keys using keys method
Output:
ChainMap({'A': 12, 'B': 12}, {'S': 11, 'Q': 21}, {'X': 88, 'Y': 12})
12
ValuesView(ChainMap({'A': 12}, {'S': 11}, {'X': 88}))
KeysView(ChainMap({'A': 12}, {'S': 11}, {'X': 88}))

Adding New Dictionary in ChainMap

It uses the new_child method to add a new dictionary to Chain Maps so that new content can be easily uploaded to Chain Map.

from collections import ChainMap

d1 = {"A": 12}
d2 = {"S": 11}
d3 = {"X": 88}
d4 = {"B": 44}

x = ChainMap(d1 , d2 , d3)

x = x.new_child(d4)
print(x)
Output:
ChainMap({'B': 44}, {'A': 12}, {'S': 11}, {'X': 88})

NamedTuple In Collections Module

NamedTuple offers us a function like the object call function in the same classes, so we can call sub-attributes as if calling an object.

from collections import namedtuple

Car = namedtuple("Cars" , ["model" , "year"])

xCarModel = Car("X Model" , 2021)

print("Car Model:" , xCarModel.model , "Year:" , xCarModel.year)
Output:
Car Model: X Model Year: 2021

Leave a Reply

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