You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义支持含连字符等特殊字符串键的TypedDict类

如何创建支持带连字符键的TypedDict类

Python中普通变量名不允许包含连字符这类特殊字符,直接在TypedDict类里写justify-content: ...会触发语法错误。要支持这类键,有两种简单可行的方法:

方法一:用字符串字面量声明特殊键

在TypedDict类定义中,把带连字符或其他非合法标识符的键用引号括起来,mypy、pyright等类型检查器会正确识别这些键。示例代码:

from typing import TypedDict, Literal
from typing_extensions import NotRequired

class Attributes(TypedDict):
    width: NotRequired[str]
    height: NotRequired[str]
    direction: NotRequired[Literal["row", "column"]]
    "justify-content": NotRequired[Literal["start", "end", "center", "equally-spaced"]]

方法二:使用字典式定义语法

如果需要定义大量带特殊字符的键,可以直接通过TypedDict构造函数传入键值对字典来创建类型,写法更灵活:

from typing import TypedDict, Literal
from typing_extensions import NotRequired

Attributes = TypedDict(
    'Attributes',
    {
        'width': NotRequired[str],
        'height': NotRequired[str],
        'direction': NotRequired[Literal["row", "column"]],
        'justify-content': NotRequired[Literal["start", "end", "center", "equally-spaced"]]
    }
)

如果所有字段都是可选的,还可以在构造函数中添加total=False参数,省去给每个字段加NotRequired的步骤:

Attributes = TypedDict(
    'Attributes',
    {
        'width': str,
        'height': str,
        'direction': Literal["row", "column"],
        'justify-content': Literal["start", "end", "center", "equally-spaced"]
    },
    total=False
)

内容的提问来源于stack exchange,提问作者Evyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:06:28