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.
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.
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.
@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.
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.
Why not just list
?
>>> list(g) [1, 'hello', 'Janitor']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With