Make a dictionary from a line of words.
What to build
A dictionary built with one comprehension.
Requirements
- Read a line of words.
- Build a dictionary from each word to its length, using one comprehension.
- Print the dictionary with
print.
Input
One line of words separated by spaces.
Output
The dictionary.
Constraints
There are from 1 to 100 words. A repeated word appears once in the result.
Example
Input:
cat horse
Output:
{'cat': 3, 'horse': 5}
Why it works
Each pass produces a key and a value, and a repeated key simply replaces its earlier entry, which has the same length anyway.
Examples
Example 1 · Input
cat horse
Expected output
{'cat': 3, 'horse': 5}
Example 2 · Input
a
Expected output
{'a': 1}
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A dictionary comprehension uses curly brackets and key: value.
Hint 2
print shows a dictionary in Python's own format.
Solution
Show one correct solution (try it yourself first)
words = input().split()
print({word: len(word) for word in words})