Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to namedtuple

Tags:

python

People also ask

How do I get Namedtuple value?

From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

How do I change Namedtuple value?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.

What is difference between Namedtuple and tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.


You can do Row(*A) which using argument unpacking.

>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row(*A)
Row(first='1', second='2', third='3')

Note that if your linter doesn't complain too much about using methods which start with an underscore, namedtuple provides a _make classmethod alternate constructor.

>>> Row._make([1, 2, 3])

Don't let the underscore prefix fool you -- this is part of the documented API for this class and can be relied upon to be there in all python implementations, etc...


The namedtuple Subclass has a method named '_make'. Inserting an Array (Python List) into a namedtuple Objects it's easy using the method '_make':

>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row._make(A)
Row(first='1', second='2', third='3')

>>> c = Row._make(A)
>>> c.first
'1'