Advanced Collections in Python
There are four different types of collections in Python:
The list() constructor returns a list in Python.
Example: Create a list from an iterator object
# objects of this class are iterators
class PowerTwo:
def __init__(self, max):
self.max = max
def __iter__(self):
self.num = 2
return self
def __next__(self):
if (self.num >= self.max):
raise StopIteration
result = 2 ** self.num
self.num += 1
return result
pow_two = PowerTwo(9)
pow_two_iter = iter(pow_two)
print(list(pow_two_iter))
Output:
[4, 8, 16, 32, 64, 128, 256]
Process finished with exit code 0
We have to use "import collections" function to call these ones.
namedTuple
Python includes a container-like dictionaries function called "namedtuple()" in the "collections" package. They, like dictionaries, include keys that are hashed to a certain value. On the contrary, it provides both key-value and iteration access, whereas dictionaries do not.
# Python code to demonstrate namedtuple()
from collections import namedtuple
# Declaring namedtuple()
Employee = namedtuple('Employee', ['name', 'age', 'DOB'])
# Adding values
S = Employee('Jack', '23', '2541997')
# Access using index
print("The Employee age using index is : ", end="")
print(S[1])
# Access using name
print("The Employee name using keyname is : ", end="")
print(S.name)
Output:
The Employee age using index is : 23
The Employee name using keyname is : Jack
Process finished with exit code 0
OrderedDict
An OrderedDict is a subclass of dictionary that remembers the order in which keys were initially placed. The sole distinction between dict() and OrderedDict() is:
Example:
# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
d = {}
for key, value in d.items():
print(key, value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 5
od['b'] = 7
od['c'] = 9
od['d'] = 11
for key, value in od.items():
print(key, value)
Result:
This is an Ordered Dict:
a 5
b 7
c 9
d 11
Process finished with exit code 0