0
0
Pythonprogramming~10 mins

Basic dictionary comprehension in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a dictionary with numbers as keys and their squares as values.

Python
squares = {x: x[1]2 for x in range(1, 6)}
print(squares)
Drag options to blanks, or click blank then click option'
A*
B+
C//
D**
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using '+' instead of '**' will add 2 to x, not square it.
Using '*' will multiply x by 2, not square it.
2fill in blank
medium

Complete the code to create a dictionary with words as keys and their lengths as values.

Python
words = ['apple', 'banana', 'cherry']
lengths = {word: [1] for word in words}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Cword.upper()
Dword[0]
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using word.upper() returns the uppercase word, not its length.
3fill in blank
hard

Fix the error in the dictionary comprehension to create a dictionary with numbers as keys and their cubes as values.

Python
cubes = {n: n[1]3 for n in range(1, 5)}
print(cubes)
Drag options to blanks, or click blank then click option'
A*
B**
C+
D//
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using '*' multiplies n by 3 instead of cubing it.
Using '+' adds 3 to n instead of cubing it.
4fill in blank
hard

Complete the code to create a dictionary with words as keys and their first letters as values, but only for words longer than 5 letters.

Python
words = 'apple', 'banana', 'cherry', 'date']
result = {word: word[0 for word in words if len(word) [1] 5}
print(result)
Drag options to blanks, or click blank then click option'
A[
B>
C<
D]
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using parentheses instead of brackets for indexing.
Using '<' instead of '>' in the condition.
5fill in blank
hard

Fill both blanks to create a dictionary with uppercase words as keys and their lengths as values, but only for words with length less than 6.

Python
words = ['apple', 'banana', 'cherry', 'date']
result = {word.upper(): {BLANK_2}} for word in words if len(word) {{BLANK_2}} 6
print(result)
Drag options to blanks, or click blank then click option'
A{word.upper()}
Blen(word)
C<
D{
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Forgetting the opening brace for the dictionary comprehension.
Using '>' instead of '<' in the condition.
Using the word itself instead of its length for values.