Junior — Middle
Can you name the main features of using the dictionary annotation?
sobes.tech AI
Answer from AI
The dictionary annotation in Python is used to specify the types of keys and values in a dictionary. Main features:
- Allows static analyzers and IDEs to check type correctness.
- Used with
typing.Dictor with dictionary syntax in newer Python versions (e.g.,dict[str, int]). - Does not affect program execution, serving only for documentation and type checking.
Example:
from typing import Dict
def count_words(text: str) -> Dict[str, int]:
words = text.split()
counts: Dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
Here, it indicates that the function returns a dictionary with keys of type str and values of type int.