NamedTuple is a more readable tuple, it can have names for itself and its elements.
# tuple
point = (1, 2)
point[0] # 1
point[1] # 2
# namedtuple (init like a class)
Point = namedtuple("Point", ["x", "y"])
point = Point(1, 2)
point[0] # 1
point[1] # 2
point.x # 1
point.y # 2
The first thing we need to do is to define a namedtuple
object by giving its name
and features
.
name
: stringfeatures
:- an iterable
- a string that divides the features with comma
- from other
namedtuple
using the attribute _fields
# 1
Dog = namedtuple("Dog", ["name", "age"])
# 2
Dog = namedtuple("Dog", "name, age")
# 3
Other = namedtuple("Other", "name, age")
Other._fields # ("name", "age")
Dog = namedtuple("Dog", [*Other._fields, "height"])
_make
is a class method that makes a new instance from an existing sequence or iterable.
Dog = namedtuple("Dog", "name, age")
# from list
feature_list = ["happy", 3]
Dog._make(feature_list)
# from tuple #1
feature_tuple = ("happy", 3)
Dog._make(feature_tuple)
# from tuple #2
features = "happy", 3
Dog._make(features)
# from dict values
feature_dict = {"name": "happy", "age": 3}
Dog._make(feature_dict.values())
_asdict
is a class method that converts the current namedtuple
into an OrderedDict
instance (in Python 3.8).
Dog = namedtuple("Dog", "name, age")
dog = Dog("happy", 3)
dog._asdict() # OrderedDict([('name', 'happy'), ('age', 3)])
_replace
is a class method that returns a new namedtuple
replacing specified features with new values.
Dog = namedtuple("Dog", "name, age")
dog = Dog("happy", 3)
dog = dog._replace(age=5) # Dog(name='happy', age=5)
_fields
is a class attribute, it will return a tuple of strings listing the features.
Dog = namedtuple("Dog", "name, age")
Dog._fields # ("name", "age")
dog = Dog("happy", 3)
dog._fields # ("name", "age")
Article | Link |
---|---|
collections - namedtuple() | https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields |
The Complete Python Course For Beginners | https://youtu.be/sxTmJE4k0ho?list=LL&t=15915 |