Trending September 2023 # Guide To Namedtuple Python With Examples # Suggested October 2023 # Top 13 Popular |

Trending September 2023 # Guide To Namedtuple Python With Examples # Suggested October 2023 # Top 13 Popular

You are reading the article Guide To Namedtuple Python With Examples updated in September 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested October 2023 Guide To Namedtuple Python With Examples

Introduction to Namedtuple Python

Web development, programming languages, Software testing & others

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


import collections Employee = collections.namedtuple('Employee',['name','age','designation']) E = Employee('Alison','30','Software engineer') print ("Demonstration using index, The Employee name is: ", print ("Demonstration using keynames, The Employee age is : ",E[1]) print ("Demonstration using getattr(), The Employee designation is : ",getattr(E,'designation'))

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


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'))


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”.


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 –

You're reading Guide To Namedtuple Python With Examples

Update the detailed information about Guide To Namedtuple Python With Examples on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!