Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a namedtuple into a list of values and preserving the order of properties?

Tags:

python

from collections import namedtuple Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient']) g = Gaga(id=1, subject='hello', recipient='Janitor') 

I want to be able to obtain this list (which preserves the order of the properties):

[1, 'hello', 'Janitor'] 

I could create this list myself manually but there must be an easier way. I tried:

g._asdict().values() 

but the properties are not in the order I want.

like image 932
canadadry Avatar asked Aug 02 '11 08:08

canadadry


People also ask

How do I get values from Namedtuple?

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.

Can Namedtuple be pickled?

@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.

What does Namedtuple on a collection type return?

Using namedtuple to Write Pythonic Code. Python's namedtuple() is a factory function available in collections . It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj.


1 Answers

Why not just list?

>>> list(g) [1, 'hello', 'Janitor'] 
like image 144
Roman Bodnarchuk Avatar answered Oct 06 '22 08:10

Roman Bodnarchuk