Challenge - 5 Problems
Safe Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of safe dictionary access with get()
What is the output of this Python code snippet?
Python
data = {'name': 'Alice', 'age': 30}
result = data.get('city', 'Unknown')
print(result)Attempts:
2 left
๐ก Hint
get() returns the value for the key if it exists, otherwise the default value.
โ Incorrect
Since 'city' is not a key in the dictionary, get() returns the default value 'Unknown'.
โ Predict Output
intermediate2:00remaining
Using get() without default value
What will this code print?
Python
info = {'x': 10, 'y': 20}
print(info.get('z'))Attempts:
2 left
๐ก Hint
If no default is given, get() returns None for missing keys.
โ Incorrect
The key 'z' is missing, so get() returns None by default.
โ Predict Output
advanced2:00remaining
Nested dictionary safe access with get()
What is the output of this code?
Python
profile = {'user': {'name': 'Bob', 'age': 25}}
age = profile.get('user', {}).get('age', 'Not found')
print(age)Attempts:
2 left
๐ก Hint
get() can be chained safely to avoid errors on missing keys.
โ Incorrect
Both keys exist, so the age 25 is returned and printed.
โ Predict Output
advanced2:00remaining
Safe access with get() and missing nested key
What will this code print?
Python
data = {'settings': {'theme': 'dark'}}
mode = data.get('settings', {}).get('mode', 'default')
print(mode)Attempts:
2 left
๐ก Hint
If the nested key is missing, get() returns the default value.
โ Incorrect
The key 'mode' is missing inside 'settings', so 'default' is returned.
๐ง Conceptual
expert3:00remaining
Behavior of get() with mutable default argument
Consider this code:
my_dict = {}
value = my_dict.get('key', [])
value.append(1)
print(my_dict)
What will be printed?
Attempts:
2 left
๐ก Hint
get() returns the default but does not insert it into the dictionary.
โ Incorrect
The default list is returned and modified, but the dictionary remains empty because get() does not add the key.