import collections
# create a named tuple called Person with fields of first_name, last_name, and age
Person = collections.namedtuple('Person', ('first_name', 'last_name', 'age'))
# Note a named tuple can have fields names as string using a space as a delimiter also see example below
Person = collections.namedtuple('Person', 'first_name last_name age')
# initialize a user as a Person Tuple
user = Person(first_name="John", last_name="Doe", age=21)
# print user named tuple
print(user)
# print user by field names
print(user.first_name, user.last_name, user.age)
# print length of user
print(len(user))
# print first name by index
print(user[0])
# loop through user
for item in user:
print(item)
# Python code to demonstrate namedtuple() and
# _make(), _asdict() and "**" operator
# importing "collections" for namedtuple()
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student',
['name', 'age', 'DOB'])
# Adding values
S = Student('Nandini', '19', '2541997')
# initializing iterable
li = ['Manjeet', '19', '411997']
# initializing dict
di = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'}
# using _make() to return namedtuple()
print("The namedtuple instance using iterable is : ")
print(Student._make(li))
# using _asdict() to return an OrderedDict()
print("The OrderedDict instance using namedtuple is : ")
print(S._asdict())
# using ** operator to return namedtuple from dictionary
print("The namedtuple instance from dict is : ")
print(Student(**di))
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')
# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4
# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)
# Like tuples, namedtuples are immutable:
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"