You can consider the collections.namedtuple
type to create tuple-like objects that have fields accessible by attribute lookup.
collections.namedtuple(typename, field_names[, verbose])
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__()
method which lists the tuple contents in a name=value format.
>>> import collections
>>> mytup = collections.namedtuple( mytup , [ tag , name , values ])
>>> e1 = mytup( tag1 , great ,[1, two ,3])
>>> e1
mytup(tag= tag1 , name= great , values=[1, two , 3])
>>> e1.values
[1, two , 3]
>>>
Building on other answers, an example of filtering a list of mytup
objects:
>>> tlist = [mytup("foo", "dog", [1,2,3,4]),
mytup("bar","cat", [4,5,6,7,8,9]), mytup("moo","cow", [4,5,7,8,9,1,3,4,65])]
>>> tlist
[mytup(tag= foo , name= dog , values=[1, 2, 3, 4]),
mytup(tag= bar , name= cat , values=[4, 5, 6, 7, 8, 9]),
mytup(tag= moo , name= cow , values=[4, 5, 7, 8, 9, 1, 3, 4, 65])]
>>> [t for t in tlist if t.tag == bar ]
[mytup(tag= bar , name= cat , values=[4, 5, 6, 7, 8, 9])]
>>>
Namedtuple
objects can, of course, be used in other structures (e.g a dict
), as mentioned in other answers. The advantage is, obviously, that the fields are named, and code using them is clearer.