Python’s collections
module provides various specialized container datatypes, such as deque
, Counter
, and defaultdict
. Another container datatype that is part of this module is the namedtuple
. namedtuple
is a subclass of Python’s built-in tuple
class, which allows us to give names to each element in a tuple. This can make our code more readable and self-documenting. In this article, we will learn how to create and use namedtuple
in Python.
Creating a namedtuple
To create a namedtuple
, we need to first import the collections
module and then define a new subclass of tuple
. In the subclass definition, we specify the names of the fields (i.e., elements) in the tuple using a string with whitespace or commas separating the field names.
from collections import namedtuple
Person = namedtuple('Person', 'name age gender')
In this example, we define a new namedtuple
subclass called Person
, which has three fields: name
, age
, and gender
. We pass two arguments to the namedtuple
constructor: the name of the new subclass and the names of the fields as a string.
We can now create instances of this new namedtuple
class:
p1 = Person('Alice', 25, 'female')
p2 = Person('Bob', 30, 'male')
print(p1)
print(p2)
Output:
Person(name='Alice', age=25, gender='female')
Person(name='Bob', age=30, gender='male')
In this example, we create two instances of the Person
namedtuple
class, p1
and p2
. We pass values for each field in the same order they were specified in the namedtuple
definition.
Accessing fields
We can access the fields of a namedtuple
instance using dot notation or indexing:
print(p1.name)
print(p2[1])
Output:
Alice
30
In this example, we access the name
field of p1
using dot notation and the age
field of p2
using indexing.
Modifying fields
namedtuple
instances are immutable, meaning we cannot modify their fields directly. However, we can create a new namedtuple
instance with some or all of the same fields updated using the ._replace()
method:
p1 = p1._replace(age=26)
print(p1)
Output:
Person(name='Alice', age=26, gender='female')
In this example, we create a new namedtuple
instance called p1
with the same values as the previous instance, but with the age
field updated to 26. We use the ._replace()
method, which returns a new namedtuple
instance with the specified fields updated.
Supported functions
namedtuple
supports many of the same functions as regular tuples, such as indexing, slicing, and iterating over elements. Additionally, namedtuple
provides some additional functions:
_asdict()
The _asdict()
method returns an ordered dictionary mapping the field names to their corresponding values:
print(p1._asdict())
Output:
OrderedDict([('name', 'Alice'), ('age', 26), ('gender', 'female')])
In this example, we call the _asdict()
method on the p1
instance to obtain an ordered dictionary that maps the field names to their values.
_fields
The _fields
attribute returns a tuple of the field names in the namedtuple
subclass:
print(Person._fields)
Output:
('name', 'age', 'gender')
In this example, we access the _fields
attribute of the Person
namedtuple
subclass to obtain a tuple of the field names.
TOP PAYING JOBS REQUIRE THIS SKILL
ENROLL AT 90% OFF TODAY
_replace()
As mentioned earlier, the _replace()
method returns a new namedtuple
instance with some or all of the same fields updated:
p3 = p1._replace(name='Charlie', gender='male')
print(p1)
print(p3)
Output:
Person(name='Alice', age=26, gender='female')
Person(name='Charlie', age=26, gender='male')
In this example, we create a new namedtuple
instance called p3
with the same values as the previous instance p1
, but with the name
and gender
fields updated. We then print both instances to show that p1
has not been modified.
Conclusion
In this article, we learned how to use Python’s collections.namedtuple
class to create tuples with named fields. We saw how to create a new namedtuple
subclass, access and modify fields, and use some of the supported functions. namedtuple
is a powerful tool for creating readable and self-documenting code, particularly for working with data structures that contain a fixed set of fields.