How to define a TypedDict class with keys containing hyphens

Viewed 63

How can I create a TypedDict class that supports keys containing hyphens or other characters that are supported in strings, such as "justify-content" in the example below.

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"]]
1 Answers

It is possible with the functional syntax:

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"]
        ],
    },
)

It's mentioned in the documentation

The functional syntax should also be used when any of the keys are not valid identifiers, for example because they are keywords or contain hyphens

Related