Problem: You want to access the element by name to reduce the dependency on the location in the structure
Solution: Use the named Tuple collections.namedtuple (). It is a factory method that returns a subclass of the standard tuple type in Python, gives it a type name and the corresponding field name , returns a class that can be instantiated, gives you a defined field name to pass in the value, and so on.
The primary purpose of a named tuple is to decouple the code from the location of the element it controls
>>> fromCollectionsImportNamedtuple>>> Sub=namedtuple ('Subscriber',['Addr','joined'])>>> Subscriber=sub ('[email protected]','2016-8-7')>>>Subscribersubscriber (Addr='[email protected]', joined='2016-8-7')>>>subscriber.addr'[email protected]'>>>subscriber.joined'2016-8-7'
Namedtuple instances are interchangeable with ordinary tuples and support operations supported by all common tuples, such as indexing and decomposition (unpacking).
>>> len (subscriber)2>>> addr,joined=subscriber>>> addr' [email protected]'>>> joined'2016-8-7'
"Python Cookbook" "Data Structure and algorithm" 18. Map names to elements of a sequence