2022-04-02

Extracting List of Keys from TypedDict Class

Extracting List of Keys from TypedDict Class

Python's built-in __annotations__ attribute is present in classes derived from Python's typing constructs, like TypedDict, and it stores a dictionary of declared type hints.

Here's how you can extract a list of keys from a TypedDict class:

python
from typing import TypedDict

class Movie(TypedDict):
name: str
year: int

keys = list(Movie.**annotations**.keys())
print(keys) # prints "['name', 'year']"

In this example, we have a TypedDict class Movie with the keys name and year. By using Movie.__annotations__.keys(), we are able to retrieve a view of the keys, which we then convert to a list with the list() function. The result is a list of keys, directly extracted from the TypedDict class.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!