In Python, if you have a dictionary
d = {'foo': 1, 'bar': False}
You can apply this onto a function that accept foo
and bar
keyword arguments by
def func(foo, bar):
# Do something complicated here
pass
func(**d)
But if instead, I wanted to call func
with the namedtuple defined below:
from collections import namedtuple
Record = namedtuple('Record', 'foo bar')
r = Record(foo=1, bar=False)
func(r) # !!! this will not work
What's the syntax for this?
The accessing methods of 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.
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.
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.
A namedtuple instance has a ._asdict()
method:
func(**r._asdict())
but if the namedtuple attributes are in the same order as the arguments of the function, you could just apply it as a sequence instead:
func(*r)
Here the two values of the namedtuple are applied, in order, to the keyword arguments in the function. Those two arguments can be addressed as positional arguments still, after all!
For your sample function, both work:
>>> def func(foo, bar):
... print foo, bar
...
>>> from collections import namedtuple
>>> Record = namedtuple('Record', 'foo bar')
>>> r = Record(foo=1, bar=False)
>>> func(**r._asdict())
1 False
>>> func(*r)
1 False
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