namedtuple
is a subclass of tuple
, which is used to create tuple-like objects with named fields and fixed length.
There are 3 parameters used while creating a namedtuple
.
typename
- indicates the name of namedtuple
field_names
- indicates the attributes associated with the namedtuple
defaults
- indicates the default values of the fieldsThere are 2 ways to create a namedtuple
:
typing
modulefrom typing import NamedTuple
class Address(NamedTuple):
street: str
door_no: int
country: str
collections
modulefrom collections import namedtupleAddress = namedtuple('Address', ['street', 'door_no', 'country'], defaults = ['Wall Street', '5', 'USA'])new_address = Address()print(new_address)
namedtuple
As namedtuples
are a subclass of tuples, the fields can be accessed via the index or by the name of the field. The index value of a field is tied to the order during the declaration of the namedtuple.
Consider the above Address
example. You can access the street
field by name or by using 0
as the index value.
print(new_address[0])
# OR
print(new_address.street)
list
/dict
to namedtuple
Consider a list containing the street, door number, and country. The _make()
method can be used to convert the list
to a namedtuple
.
from collections import namedtupleAddress = namedtuple('Address', ['street', 'door_no', 'country'])address_list = ['List Avenue', '23', 'USA']new_address_list = Address._make(address_list)print(new_address_list)address_dict = {'street':'Dict Avenue', 'door_no': '32', 'country':'USA'}new_address_dict = Address._make(address_dict.values())print(new_address_dict)
Name | Description |
---|---|
_fields |
To list the field names |
_asdict() |
To convert namedtuple to dict |
_field_defaults |
Default values of the fields |
_replace() |
To replace a field value of a namedtuple |
from collections import namedtupleAddress = namedtuple('Address', ['street', 'door_no', 'country'], defaults = ['Wall Street', '5', 'USA'])new_address = Address("Penn Street", "56", "USA")print("Field names:\n")print(new_address._fields)print("-" * 10)print("Field Default Values:\n")print(new_address._field_defaults)print("-" * 10)print("Tuple as dictionary:\n")print(new_address._asdict())print("-" * 10)print("Replace:\n")print(new_address._replace(street="Bourbon Street"))