Namedtuple
Namedtuple in Python
Python supports a type of container like dictionaries called namedtuples() present in module, collections. Like dictionaries they contain keys that are hashed to a particular value. But on contrary, it supports both access from key value and iteration, the functionality that dictionaries lack.
Operations on namedtuple()
namedtuple()Access Operations
Access by index : The attribute values of
namedtuple()are ordered and can be accessed using the index number unlike dictionaries which are not accessible by index.Access by keyname : Access by
keynameis also allowed as in dictionaries.using
getattr():- This is yet another way to access the value by givingnamedtupleand key value as its argument.
# Python code to demonstrate namedtuple() and
# Access by name, index and getattr()
# importing "collections" for namedtuple()
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# Access using index
print("The Student age using index is : ",end ="")
print(S[1])
# Access using name
print("The Student name using keyname is : ",end ="")
print(S.name)
# Access using getattr()
print("The Student DOB using getattr() is : ",end ="")
print(getattr(S,'DOB'))Output:
Conversion Operations
_make():- This function is used to return anamedtuple()from the iterable passed as argument._asdict():- This function returns theOrdereDict()as constructed from the mapped values ofnamedtuple().using “**” (double star) operator:- This function is used to convert a dictionary into thenamedtuple().
Output :
Additional Operations
_fields:- This function is used to return all thekeynamesof the namespace declared._replace():- This function is used to change the values mapped with the passedkeyname.
Output:
References
Last updated