Getting name of value from namedtuple

Question:

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?

Asked By: user278618

||

Answers:

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
Answered By: ars
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.

Answered By: jd.
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.