Named Tuples in Python

This tutorial deals with named tuples in Python.

Python has various data structures that can be used to store and manipulate data. One such data structure is a named tuple. The named tuple is like a dictionary in Python that stores key-value pairs. But in this, the data can be accessed using the index as well as the keys which gives it an advantage over the dictionaries in Python.

Since dictionaries are mutable and if we need to store data in an immutable container we need to use tuples. But in normal tuples, it is very difficult to remember what data is a particular tuple holding and therefore named tuples are used in which the field names can be used to access the data.

Creating a named tuple and accessing data in Python

from collections import namedtuple
marks = namedtuple('marks', 'physics chemistry maths english')
rahul = marks(85,75,60,90)
ankit = marks(96,55,45,58)
print(ankit)
print(rahul)

#accessing using index
print("Index Output")
print(rahul[0])
print(ankit[3])

#accessing using key
print("Key Output")
print(rahul.physics)
print(ankit.english)

#accesssing using getattr() method
print("getattr() Ouput")
print(getattr(rahul,'physics'))
print(getattr(ankit,'english'))

Output:

marks(physics=96, chemistry=55, maths=45, english=58)
marks(physics=85, chemistry=75, maths=60, english=90)
Index Ouput
85
58
Key Output
85
58
getattr() Output
85
58

Here, we see that every method of accessing the data stored in the named tuple gives the same ouput. Therefore, anyone can be used according to the requirements.

Conversion to named tuples

lst = [60,70,85,40]
vijay = marks._make(lst) #using _make() function
print(vijay)

my_dict = {'physics':35, 'chemistry':96, 'maths':39, 'english':55}
gauri = marks(**my_dict) ##using '**' operator
print(gauri)

print(rahul._asdict())

Output:

marks(physics=60, chemistry=70, maths=85, english=40)
marks(physics=35, chemistry=96, maths=39, english=55)
OrderedDict([('physics', 85), ('chemistry', 75), ('maths', 60), ('english', 90)])
  • In the first case, a list is converted to a tuple. This can be done using the _make() function.
  • Then a dictionary is converted to a named tuple. This was done using the ‘**’ operator.
  • The _asdict() method is used to generate the OrderedDict().

Also read: How to check if a tuple has any None value in Python

Leave a Reply

Your email address will not be published. Required fields are marked *