将 NamedTuple 转换为 dict 以用于字典解包的 Pythonic 方法 (**kwargs)

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

我有一个 typing.NamedTuple,我想将其转换为 dict,以便我可以通过字典解包传递给一个函数:

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))

什么是最 Pythonic 实现此目的的方法?我正在使用 Python 3.8+.


更多详情

这里有一个示例 NamedTuple 可以使用:

from typing import NamedTuple

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

foo = Foo(1.0)

尝试 kwarg_func(**dict(foo)) 引发 TypeError:

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

_asdict() 作品:

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

但是,由于_asdict是私有的,我想知道,有没有更好的方法?

使用._asdict.

._asdict 不是私有的。它是 public,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.