Recall & Review
beginner
What does the
get() method do in a Python dictionary?It safely retrieves the value for a given key. If the key is not found, it returns
None or a specified default value instead of raising an error.Click to reveal answer
beginner
How do you provide a default value when using
get()?You pass the default value as the second argument to
get(). For example, my_dict.get('key', 'default') returns 'default' if 'key' is missing.Click to reveal answer
beginner
Why is using
get() safer than directly accessing a dictionary key?Direct access like
my_dict['key'] raises a KeyError if the key is missing. get() avoids this by returning None or a default value, preventing program crashes.Click to reveal answer
beginner
What will
my_dict.get('age', 30) return if 'age' is not in my_dict?It will return
30, the default value provided.Click to reveal answer
intermediate
Can
get() be used with nested dictionaries to avoid errors?Yes, but only for one level at a time. For nested dictionaries, you can chain
get() calls or use other methods to safely access deeper keys.Click to reveal answer
What does
my_dict.get('key') return if 'key' is not present?✗ Incorrect
get() returns None by default if the key is missing.How do you specify a default value of 100 when using
get()?✗ Incorrect
The second argument to
get() is the default value returned if the key is missing.Which of these will cause a program crash if the key is missing?
✗ Incorrect
Direct access with square brackets raises
KeyError if the key is missing.What type of object is
get() called on?✗ Incorrect
get() is a method of Python dictionaries.If
my_dict = {'a': {'b': 2}}, what does my_dict.get('a').get('b') return?✗ Incorrect
First
get('a') returns the nested dict, then get('b') returns 2.Explain how the
get() method helps avoid errors when accessing dictionary keys.Think about what happens if the key is missing.
You got /4 concepts.
Describe how to use
get() with a default value and why it is useful.What do you pass to <code>get()</code> besides the key?
You got /4 concepts.