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

2024-05-13 11:10:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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))

实现这一目标的最具Python风格的方式是什么?我正在使用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

根据this post on ^{}_asdict()工程:

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

然而,既然_asdict是私有的,我想知道,有没有更好的办法


Tags: 函数truetyping字典foothisnamedtupledict
1条回答
网友
1楼 · 发布于 2024-05-13 11:10:27

使用._asdict

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

相关问题 更多 >