0
0
Pythonprogramming~10 mins

Safe access using get() 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 safely get the value for key 'name' from the dictionary.

Python
person = {'name': 'Alice', 'age': 30}
name = person.[1]('name')
print(name)
Drag options to blanks, or click blank then click option'
Aget
Bpop
Ckeys
Dvalues
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using person['name'] which causes error if key is missing
Using pop which removes the key from dictionary
2fill in blank
medium

Complete the code to get the value for 'city' with a default of 'Unknown'.

Python
location = {'country': 'USA'}
city = location.[1]('city', 'Unknown')
print(city)
Drag options to blanks, or click blank then click option'
Aget
Bpop
Csetdefault
Dupdate
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using pop which removes the key
Using setdefault which adds the key if missing
3fill in blank
hard

Fix the error by completing the code to safely access 'score' from the dictionary.

Python
results = {'player': 'Bob'}
score = results.[1]('score')
print(score)
Drag options to blanks, or click blank then click option'
Aclear
Bget
Cpopitem
Dkeys
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using popitem which removes an arbitrary item
Using keys which returns all keys, not a value
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths only for words longer than 3 letters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2] > 3}
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using word instead of len(word) for length
Checking word instead of its length in condition
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values only if value is positive.

Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using original key instead of uppercase
Using wrong comparison operator
Using key instead of value for dictionary values