Introduction to Namedtuple Python
In Python, there are different types of containers like lists, set, dictionaries, etc. These containers can be used in programs to collect data; to do this in Python, we have collection modules which are an alternative to Python containers. These collection modules have different data structures to collect and store a set of data one such module is namedtuple. In Python, namedtuple is a function module of a collection module that returns tuple or set of data where each data in a set or tuple is named. In general, every value in the tuple is given a name so that it will be easy to access each value by its name.
Working of Namedtuple
As tuple has an integer index to access as they have no names, there might be ambiguity to store and access the data to that particular integer index. Tuples are an ad-hoc structure that means if two tuples have the same number of fields and the same data stored, there is an ambiguity for accessing. So to overcome all such problems, Python introduces Namedtuple in the collections module. Python has containers like dictionaries called namedtuple(), supporting access to the value through key similar to dictionaries. Namedtuple is the class of collections module which also contains many other classes for storing data like sets, dictionaries, tuple, etc.
Nametuple is an extension to the built-in tuple data type, where tuples are immutable, which means once created, they cannot be modified. Here it shows how we can access the elements using keys and indexes. To use this namedtuple(), you should always import collections in the program. Namedtuples offers a few users access and conversion methods that all start with a _ underscores. Namedtuple is mostly used on unstructured tuples and dictionaries, which makes it easier for data accessing. Namedtuple makes an easy way to clean up the code and make it more readable, which makes it a better structure for the data.
There are different access and conversion operations on namedtuple.
They are as follows:
Access operations on Namedtuple() which we can access values using indexes, keys, and getattr() methods.
- Access by index: In this, the values are accessed using index number because the attribute values of namedtuple() are in order so indexes can easily access it.
- Access by keys: In this, the working is similar to a dictionary where the values can be accessed using the keys given as allowed in dictionaries.
- Access using getattr(): This is one of another method in which it takes namedtuple and key-value as its argument.
Examples of Namedtuple Python
Given below are the examples mentioned:
Example #1
Code:
import collections
Employee = collections.namedtuple('Employee',['name','age','designation'])
E = Employee('Alison','30','Software engineer')
print ("Demonstration using index, The Employee name is: ",E.name)
print ("Demonstration using keynames, The Employee age is : ",E[1])
print ("Demonstration using getattr(), The Employee designation is : ",getattr(E,'designation'))
Output:
In the above example, firstly, we create namedtuple() with tuple name as “Employee”, and it has different attributes in the tuple named “name”, “age”, “designation”. The Employee tuple’s key-value can be accessed using 3 different ways, as demonstrated in the program.
There are some conversion operations that can be applied on namedtuple().
They are as follows:
- _make(): This function converts any iterable passed as argument to this function to namedtuple() and this function returns namedtuple().
- _asdict(): This function converts the values of namedtuple that are constructed by mapping the values of namedtuple and returns the OrderDict().
- ** (double star) operator: This operator is used to convert to namedtuple() from the dictionary.
- _fields: This function returns all the keynames of the namedtuple that is declared. We can also check how many fields and which fields are there in the namedtuple().
- _replace(): This function replaces the values that are mapped with keynames that are passed as an argument to this function.
Example #2
Demonstration of all the above conversion operations on namedtuple().
Code:
import collections
Employee = collections.namedtuple('Employee',['name','age','designation'])
E = Employee('Alison','30','Software engineer')
El = ['Tom', '39', 'Sales manager' ]
Ed = { 'name' : "Bob", 'age' : 30 , 'designation' : 'Manager' }
print ("The demonstration for using namedtuple as iterable is : ")
print (Employee._make(El))
print("\n")
print ("The demonstration of OrderedDict instance using namedtuple is : ")
print (E._asdict())
print("\n")
print ("The demonstration of converstion of namedtuple instance to dict is :")
print (Employee(**Ed))
print("\n")
print ("All the fields of Employee are :")
print (E._fields)
print("\n")
print ("The demonstration of replace() that modifies namedtuple is : ")
print(E._replace(name = 'Bob'))
Output:
The above program creates the namedtuple() “Employee” and then it creates iterable list and dictionary “El” and “Ed” which uses the conversion operations _make() which will convert the “El” to namedtuple(), _asdict() is also used to display the namedtuple() in the order that is using OrderDict(), the double start (**) which converts dictionary “Ed” to namedtuple(), E.fields which will print the fields in the declared namedtuple(), E.replace(name = “Bob”) this function will replace the name field value of the namedtuple() in this it replaces “Alison” to “Bob”.
Conclusion
In Python, we use namedtuple instead of the tuple as in other programming languages as this is a class of collections module that will provide us with some helper methods like getattr(), _make(), _asdict(), _fileds, _replace(), accessing with keynames, ** double star, etc. This function helps us access the values by having keys as the arguments with the above different access and conversion functions on the namedtuple() class of collections module. It is easier than tuples to use and is very efficient and readable than tuples.
Recommended Articles
This is a guide to Namedtuple Python. Here we discuss the introduction, working of namedtuple python along with examples. You may also have a look at the following articles to learn more –