This Python tutorial will discuss namedtuple, one of the factory functions of the collections’ module. We will go through all the important concepts of Python namedtuple with examples and syntax.
What is Namedtuple in Python?
Namedtuple is a function of the Python collections module, an extension of the Python tuple data container that lets us access elements in a tuple using names or labels. We can define a new tuple class by importing namedtuple from the Python collections module and use the namedtuple() factory function. In short, a named tuple is a combination of Python tuple and dict data type.
Python Namedtuple Syntax
tuple_name = namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Among the 6 attributes of namedtuple(), only two are mandatory, typename and fields_name, the rest are optional.
The typename represents the tuple subclass name, and it is used to create tuple-like objects.
The feild_names attribute represents the label name for the tuple elements. It can be a string separated by spaces “fname lname dept salary” or a list of string [‘fname’, ‘lname’, ‘dept’, ‘salary’].
Declaring a Namedtuple in Python
Now, let’s begin with declaring a namedtuple.
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#add values to the named tuple
e1 = Employee('Sam', 'Smith', 'Marketing', 20000)
#access value with label
print("The name of Employee e1 is:", e1.fname +" "+ e1.lname)
#access value using the index value
print("The dept of the Employee e1 is:", e1[2])
Output:
The dept of the Employee e1 is: Marketing
Accessing Elements from the Namedtuple in Python
There are three ways to access elements from a named tuple using:
- index (like a tuple)
- field name/label name (like a dictionary)
- getattr() method
#Declaring the namedtuple:
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#adding values to the named tuple:
e1 = Employee('Sam', 'Smith', 'Marketing', 20000)
#accessing value using index value:
print("Employee (using index)", e1[0], e1[1], e1[2], e1[3])
#accessing value with label:
print("Employee (using label)", e1.fname, e1.lname, e1.dept, e1.salary)
#accessing value using getattr():
print("Employee (using getattr())", getattr(e1,'fname'), getattr(e1,'lname'), getattr(e1,'dept'), getattr(e1,'salary'))
Output:
Employee (using label) Sam Smith Marketing 20000
Employee (using getattr()) Sam Smith Marketing 20000
Working with Python Namedtuple
Python Namedtuples is Immutable
Like a normal tuple, namedtuples are also immutable. It will throw an error if we assign a new value to an existing index number or label.
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#add values to the named tuple
e1 = Employee('Sam', 'Smith', 'Marketing', 20000)
e1.fname ="John" #error
Output:
Converting a Python Named Tuple into a Python Dictionary
A namedtuple is treated as a dictionary because every element of the named tuple is associated with a label like in a Python dictionary.
To convert a namedtuple into a dictionary, we can use the ._asdict() method.
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#add values to the named tuple
e1 = Employee('Sam', 'Smith', 'Marketing', 20000)
print(e1._asdict())
Output:
Create a Namedtuple from Python Iterable Object
To convert an iterable object like tuple, list, set, and dictionary into namedtuple, we can use the namedtuple’s ._make() method.
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#list
e1 = ['Rahul', 'Sharma', 'Marketing', 20000]
#tuple
e2 = ('Ravi', 'Kumar', 'Marketing', 20000)
print(Employee._make(e1))
print(Employee._make(e2))
Output:
Employee(fname='Ravi', lname='Kumar', dept='Marketing', salary=20000)
Convert a Python Dictionary into the Named Tuple
There are two ways to convert a Python dictionary to a namedtuple.
We can either use the ** operator or dictionary values() method.
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#dictionary
e1 ={'fname':'Sonia', 'lname':'Jenner', 'dept':'Management', 'salary':20000}
#using ** operator
print(Employee(**e1))
#using ._make() method
print(Employee._make(e1.values()))
Output:
Employee(fname='Sonia', lname='Jenner', dept='Management', salary=20000)
Check All the Fields of Python Named Tuple
Using the _fields property, we can all the fields of the named tuple
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
print(Employee._fields)
Output:
How to Change the Value of Namedtuple
A namedtuple is immutable, and we cannot change its attribute values after declaration. However, the namedtuple provides the .replace() method that returns a copy of the namedtuple with a changed attribute value.
Example:
#Declaring the namedtuple
Employee = namedtuple("Employee", ['fname', 'lname', 'dept', 'salary'])
#add values to the named tuple
e1 = Employee('Sam', 'Smith', 'Marketing', 20000)
print(e1._replace(fname='John'))
Output:
Conclusion
To conclude this Python tutorial, we learned what is namedtuple in Python and how to declare it. Namedtuple is a combination of Python tuple and Python dictionary in which elements are accessed with both label (key) or index numbers. We can use the namedtuple as a normal Python tuple container, and they come in handy when we want to perform hashing using tuple only.