Int*_*rer 0 python dictionary namedtuple iterable-unpacking
我有一个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))
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最 Pythonic 方法是什么?我正在使用 Python 3.8+。
更多细节
这是一个NamedTuple
可以使用的示例:
from typing import NamedTuple
class Foo(NamedTuple):
f: float
b: bool = True
foo = Foo(1.0)
Run Code Online (Sandbox Code Playgroud)
尝试kwarg_func(**dict(foo))
提出一个TypeError
:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Run Code Online (Sandbox Code Playgroud)
根据这篇文章collections.namedtuple
,_asdict()
作品:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Run Code Online (Sandbox Code Playgroud)
但是,既然_asdict
是私有的,我想知道,有没有更好的方法?