I have the following list
a = [[a1, b1, c1, [d1, e1, f1],
[a2, b2, c2, [d2, e2, f2],
[a3, b3, c3, [d3, e3, f3]]
How can I make this into a list of named tuples such that
a[0].val1
>>> a1
a[1].val2
>>> b2
a[0].box
>>> [d1, e1, f1]
A named tuple is an extension and custom data type that enrich built-in tuples with extra utilities. They are very useful in context where we need to create a data structure that can be accessed by both the positional index and the named attribute of the elements.
In general, you can use namedtuple instances wherever you need a tuple-like object. Named tuples have the advantage that they provide a way to access their values using field names and the dot notation. This will make your code more Pythonic.
To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.
We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.
Use the collections.namedtuple
class factory to create a named tuple class:
mynamedtuple = collections.namedtuple('mynamedtuple', ('val1', 'val2', 'val3', 'box'))
somenamedtuple = mynamedtuple('a1', 'a2', 'a3', ['d1', 'e1', 'f1'])
somenamedtuple.box # returns ['d1', 'e1', 'f1']
You can convert your existing list using a list comprehension:
a = [mynamedtuple(*el) for el in a]
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