Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting name of value from namedtuple

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?

like image 694
user278618 Avatar asked Jul 04 '11 10:07

user278618


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.

What does Namedtuple return in Python?

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.

Can a Namedtuple be a dictionary key?

YES! namedtuples are also immutable. Any immutable datatype can be used as a dictionary key!

Can Namedtuple be pickled?

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


2 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 
like image 157
ars Avatar answered Oct 14 '22 23:10

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.

like image 44
jd. Avatar answered Oct 14 '22 22:10

jd.