Explaining Type Hints for Dictionaries in Python

Pavol Kutaj
1 min readJun 8, 2023

--

The aim of this page📝 is the unpacking of the following type hint I found in one of the methods with the signature:

def get_keys(self, key_type: KeyType) -> Dict[str, str]:
  • Dict[str, str] is a type hint in Python that indicates a dictionary where the keys and values are both of type str.
  • The syntax is Dict[key_type, value_type]
  • Type hints are used to indicate the expected type of a variable or function argument/return value.
  • A dictionary with keys and values of various types can be represented using the Union type from the typing module. For example: Dict[str, Union[str, int, List[str]]].
  • Type hints in Python are not enforced at runtime.
  • Third-party tools such as mypy can be used to perform static type checking on your code.
  • The isinstance() function can be used to check if a variable is an instance of a specific type at runtime.

Example:

LINKS

--

--

No responses yet