Named Tuples

·

1 min read

Import

from collections import namedtuple

Declarations

Point1 = namedtuple('Point', ['x', 'y'])
Point2 = namedtuple('Point', 'x, y')
Point3 = namedtuple('Point', 'x y')
Point4 = namedtuple('Point', 'x y x class', rename=True) # Default = False

Creating objects

p1 = Point1(x=10, y=35)
p2 = Point2(20, 40)
p3 = Point3(45, y=20)
p4 = Point4(10, 20, 30, 40) # creates new directories called _2, _3

Why namedtuples?

Customization.

You can customize directories, so when you call them you can simply use the 'named' directories instead of an old way of calling directories like [0], or [1].

Calling customized directories

print(p1.x+p2.y) # visualize the factors by calling them .x, and .y

._fields

Returns the field of the namedtuple (for this case it would be ('x', 'y'))

print(p1._fields, p2._fields, p3._fields, p4._fields)

._asdict()

Returns OrderedDict of the namedtuple

print(p1._asdict())
print(p4._asdict())

{'x': 10, 'y': 35}

{'x': 10, 'y': 20, '_2': 30, '_3': 40}