Python namedTuples
Python supports a type of container like dictionaries called “namedtuples()” present in module, “collection“. 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() :Access Operations
1. 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.
2. Access by keyname : Access by keyname is also allowed as in dictionaries.
3. using getattr() :- This is yet another way to access the value by giving namedtuple and key value as its argument.
Example 1:
Output:
The Student age using index is : 19
The Student name using keyname is : Nandini
The Student DOB using getattr() is : 2541997
Conversion Operations
1. _make() :- This function is used to return a namedtuple() from the iterable passed as argument.
2. _asdict() :- This function returns the OrdereDict() as constructed from the mapped values of namedtuple().
3. using “**” (double star) operator :- This function is used to convert a dictionary into the namedtuple().
Example 2:
Output:
The namedtuple instance using iterable is :
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
The namedtuple instance from dict is :
Student(name='Nikhil', age=19, DOB='1391997')
Additional Operations
1. _fields :- This function is used to return all the keynames of the namespace declared.
2. _replace() :- This function is used to change the values mapped with the passed keyname.
Example 3:
Output:
All the fields of students are :
('name', 'age', 'DOB')
The modified namedtuple is :
Student(name='Manjeet', age='19', DOB='2541997')
Last updated