Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary python python-3.x typing

TypedDict when keys have non alphanumeric characters

发布于 2020-03-31 22:59:36

If I have a key in a dictonary, such as A(2). How can I create a TypedDict with this field?

E.g

from typing import TypedDict

class RandomAlphabet(TypedDict):
    A(2): str

is not valid Python code, resulting in the error:

SyntaxError: illegal target for annotation
Questioner
johng
Viewed
28
Georgy 2020-01-31 22:31

According to PEP 589 you can use alternative syntax to create a TypedDict as follows:

Movie = TypedDict('Movie', {'name': str, 'year': int})

So, in your case, you could write:

from typing import TypedDict

RandomAlphabet = TypedDict('RandomAlphabet', {'A(2)': str})