Search code examples
pythondictionarynamedtupleiterable-unpacking

Pythonic way to convert NamedTuple to dict to use for dictionary unpacking (**kwargs)


I have a typing.NamedTuple that I would like to convert to a dict so that I can pass into a function via dictionary unpacking:

def kwarg_func(**kwargs) -> None:
    print(kwargs)

# This doesn't actually work, I am looking for something like this
kwarg_func(**dict(my_named_tuple))

What is the most Pythonic way to accomplish this? I am using Python 3.8+.


More Details

Here is an example NamedTuple to work with:

from typing import NamedTuple

class Foo(NamedTuple):
    f: float
    b: bool = True

foo = Foo(1.0)

Trying kwarg_func(**dict(foo)) raises a TypeError:

TypeError: cannot convert dictionary update sequence element #0 to a sequence

Per this post on collections.namedtuple, _asdict() works:

kwarg_func(**foo._asdict())
{'f': 1.0, 'b': True}

However, since _asdict is private, I am wondering, is there a better way?


Solution

  • Use ._asdict.

    ._asdict is not private. It is a public, documented portion of the API. From the docs:

    In addition to the methods inherited from tuples, named tuples support three additional methods and two attributes. To prevent conflicts with field names, the method and attribute names start with an underscore.