Type Hints
Completed
Write def word_lengths(words: list[str]) -> dict[str, int] and def longest(lengths: dict[str, int]) -> str | None (returns None for an empty dict). Read words (or - for none), print the dict and the longest word.
Input
One line of words, or -.
Output
Two lines.
Example
Input
red yellow blue
Output
{'red': 3, 'yellow': 6, 'blue': 4}
yellow
Editor
Python
Hints
Type hints document intent; Python doesn't enforce them at runtime.
str | None means "a string or None".
Solution explanation
Tools like mypy and your editor use hints to catch bugs before the code runs.
Show solution
def word_lengths(words: list[str]) -> dict[str, int]:
return {w: len(w) for w in words}
def longest(lengths: dict[str, int]) -> str | None:
if not lengths:
return None
return max(lengths, key=lengths.get)
line = input()
words = [] if line == "-" else line.split()
lengths = word_lengths(words)
print(lengths)
print(longest(lengths))