2022-04-22    Share on: Twitter | Facebook | HackerNews | Reddit

Use Python TypedDict to Type Hint Dictionaries

Define types for the fields in a dictionary using TypedDict as a base class to inherit from and then use this class in hints.

from typing import TypedDict


class NameInfo(TypedDict):
    name: str
    first_letter: str


def get_info(name: str) -> NameInfo:
    return {'name': name, 'first_letter': name[0]}

from: https://stackoverflow.com/a/54198204/3247880