In this post, we will understand the operations that can be performed on the Python NamedTuple. This is a continuation of the NamedTuple Part 1. If you haven't visited that post, it is highly suggested to understand how NamedTuple works and the various ways of creating one.
1. NamedTuple: Accessing the elements using index
As mentioned previously, elements of a dictionary can't be accessed with the help of an index, whereas elements of a NamedTuple can be accessed with the help of an index using square brackets ([]
).
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
print ("Website name using index is : ",end ="")
print (my_website[0])
Output:
Website name using index is : Studytonight
2. NamedTuple: Accessing the elements using key
This feature can be seen in dictionaries as well, i.e accessing the value with the help of the name associated with it. This can be achieved with the help of the dot operator in NamedTuple.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
print(my_website.Type)
Output:
Student friendly
3. NamedTuple: Using the built-in method getattr()
The getattr()
is a built-in method that can be used to access the value of the key associated with a specific namedtuple
. It can be achieved by passing the name of the NamedTuple and the value that needs to be found.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
print(getattr(my_website,'number_of_characters'))
Output:
12
Until now, we discussed how namedtuple
name and values associated with the key of the NamedTuple can be accessed with the help of index, key and the built-in method getattr()
. Now we will look at how an iterable can be converted into a NamedTuple.
NamedTuple: The _make
method
This method takes an iterable as an argument and constructs a NamedTuple from it and returns it. In the below example, we will construct a new list and store the values of the key associated with a NamedTuple in it. We then use the _make
method to convert it into a NamedTuple.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
new_data = ['Studytonight_one', 'Helpful', 16]
my_website._make(new_data)
Output:
Website_details(Name='Studytonight_one', Type='Helpful', number_of_characters=16)
Conversion from a dictionary to a NamedTuple
The double star (**
) operator can be used to convert a dictionary data structure into a NamedTuple. A new dictionary is created that stores the key values which are later passed to NamedTuple.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
new_data = {'Name':'Studytonight_one', 'Type':'Helpful', 'number_of_characters':16}
print(website(**new_data))
Output:
Website_details(Name='Studytonight_one', Type='Helpful', number_of_characters=16)
Conversion from NamedTuple to an OrderedDict
A NamedTuple can be converted to an OrderedDict with the help of asdict
method.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
new_data = {'Name':'Studytonight_one', 'Type':'Helpful', 'number_of_characters':16}
my_website._asdict()
Output:
OrderedDict([('Name', 'Studytonight'),
('Type', 'Student friendly'),
('number_of_characters', 12)])
Accessing all the fields of a NamedTuple and replacing certain values
When you wish to see all the fields associated with a certain key value of a NamedTuple, the _fields
method can be used. When you wish to replace a certain value with another, the _replace
method can be used.
Time for an example:
from collections import namedtuple
website = namedtuple('Website_details', ['Name', 'Type', 'number_of_characters'])
my_website = website( 'Studytonight', 'Student friendly', 12)
print(my_website._fields)
print(my_website._replace(Type='Student_friendly'))
Output:
('Name', 'Type', 'number_of_characters')
Website_details(Name='Studytonight', Type='Student_friendly', number_of_characters=12)
So, when do I use NamedTuple?
A NamedTuple can be used in many instances. A few of them are listed below:
-
When you wish to replace simple classes.
-
When the code should be more readable. Instead of using lists and tuples (which are difficult to keep track of), NamedTuple could be used.
-
When it is needed to access the data with the help of the key values.
Conclusion
In this post, we understood the different functionalities of NamedTuple. Don't forget to run the code and meddle with it to see how the output changes.