Convert list to namedtuple

Question:

In python 3, I have a tuple Row and a list A:

Row = namedtuple('Row', ['first', 'second', 'third'])
A = ['1', '2', '3']

How do I initialize Row using the list A? Note that in my situation I cannot directly do this:

newRow = Row('1', '2', '3')

I have tried different methods

1. newRow = Row(Row(x) for x in A)
2. newRow = Row() + data             # don't know if it is correct
Asked By: user1231969

||

Answers:

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…

Answered By: mgilson

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'
Answered By: Nicolás
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.