
Named Tuples
A named tuple is a function of the collections module. named tuples are a special type, or should i say, enhanced type of tuple. It generates tuples with a designated class name, as well as field names.
For example
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'make model year')
>>> CarOne = Car('Ford', 'Mustang', 2014)
>>> CarOne
Car(make='Ford', model='Mustang', year=2014)
>>> CarOne.model
'Mustang'
>>> CarOne[0]
'Ford'
A named tuple has a few useful attributes;
_fields - returns the fields of the class
_make - creates a named tuple form an iterable.
_asdict( ) - returns an OrderedDict.
>>> Car._fields
('make', 'model', 'year')
>>> CarOne._fields
('make', 'model', 'year')
>>> CarModel = namedtuple('CarModel', 'model transmission cylinder')
>>> CarTwo = ('Ford', CarModel('Mustang', 'Manual', 'GT'), 2014)
>>> newCar = Car._make(CarTwo)
>>> newCar._asdict()
OrderedDict([('make', 'Ford'), ('model', CarModel(model='Mustang', transmission='Manual', cylinder='GT')), ('year', 2014)])
>>> for key, value in newCar._asdict().items():
... print(key + ':', value)
...
('make:', 'Ford')
('model:', CarModel(model='Mustang', transmission='Manual', cylinder='GT'))
('year:', 2014)
List Comprehensions
A list