Python’s Collections module provides many useful data container types, one of which is namedtuple.
namedtuple can be used to create data types similar to tuples. In addition to being able to use indexes to access data, it can iterate, and it can also conveniently access data through attribute names.
In python, a traditional tuple is similar to an array. Each element can only be accessed through subscripts. We also need to annotate what data each subscript represents. By using namedtuple, each element has its own name, similar to the struct in C language, so that the meaning of the data can be clear at a glance. Of course, declaring namedtuple is very simple and convenient.
The code example is as follows:
from collections import namedtuple Friend=namedtuple("Friend",['name','age','email']) f1=Friend('xiaowang',33,'xiaowang@163.com') print(f1) print(f1.age) print(f1.email) f2=Friend(name='xiaozhang',email='xiaozhang@sina.com',age=30) print(f2) name,age,email=f2 print(name,age,email)
Similar to tuple, its properties are also immutable:
>>> big_yellow.age += 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute
Can be easily converted into OrderedDict:
>>> big_yellow._asdict() OrderedDict([('name', 'big_yellow'), ('age', 3), ('type', 'dog')])
When the method returns multiple values, it is actually better to return the result of namedtuple, so that the logic of the program will be clearer and easier to maintain:
>>> from collections import namedtuple >>> def get_name(): ... name = namedtuple("name", ["first", "middle", "last"]) ... return name("John", "You know nothing", "Snow") ... >>> name = get_name() >>> print name.first, name.middle, name.last John You know nothing Snow
Compared with tuple and dictionary, namedtuple is slightly more comprehensive: intuitive and easy to use. It is recommended that you use namedtuple when appropriate.