I have a module with collection:
import collections
named_tuple_sex = collections.namedtuple(
'FlightsResultsSorter',
['TotalPriceASC',
'TransfersASC',
'FlightTimeASC',
'DepartureTimeASC',
'DepartureTimeDESC',
'ArrivalTimeASC',
'ArrivalTimeDESC',
'Airlines']
)
FlightsResultsSorter = named_tuple_sex(
FlightsResultsSorter('TotalPrice', SortOrder.ASC),
FlightsResultsSorter('Transfers', SortOrder.ASC),
FlightsResultsSorter('FlightTime', SortOrder.ASC),
FlightsResultsSorter('DepartureTime', SortOrder.ASC),
FlightsResultsSorter('DepartureTime', SortOrder.DESC),
FlightsResultsSorter('ArrivalTime', SortOrder.ASC),
FlightsResultsSorter('ArrivalTime', SortOrder.DESC),
FlightsResultsSorter('Airlines', SortOrder.ASC)
)
and in another module, I iterate by this collection and I want to get the name of the item:
for x in FlightsResultsSorter:
self.sort(x)
so in the code above, I want instead of x
(which is an object) to pass, for example, DepartureTimeASC
or ArrivalTimeASC
.
How can I get this name?
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.
typename provides the class name for the namedtuple returned by namedtuple() . You need to pass a string with a valid Python identifier to this argument. field_names provides the field names that you'll use to access the values in the tuple.
YES! namedtuples are also immutable. Any immutable datatype can be used as a dictionary key!
@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.
If you're trying to get the actual names, use the _fields
attribute:
In [50]: point = collections.namedtuple('point', 'x, y') In [51]: p = point(x=1, y=2) In [52]: for name in p._fields: ....: print name, getattr(p, name) ....: x 1 y 2
from itertools import izip for x, field in izip(FlightsResultsSorter, named_tuple_sex._fields): print x, field
You can also use FlightsResultsSorter._asdict()
to get a dict.
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