300-435 · Question #23
Refer to the exhibit. What is the result when running the Python scripts?
The correct answer is B. s2. The dict.get(key, default) method returns the value associated with the specified key if it exists; otherwise, it returns the provided default value.
Question
Options
- As1
- Bs2
- Cs1, s2, s3
- Ds3
How the community answered
(45 responses)- A4% (2)
- B89% (40)
- C4% (2)
- D2% (1)
Why each option
The `dict.get(key, default)` method returns the value associated with the specified key if it exists; otherwise, it returns the provided default value.
The key `"s1"` is present, but `get()` is specifically looking for `"s2"`, so `"s1"` would not be the direct result.
Assuming the exhibit intended the dictionary values to be strings matching their keys (e.g., `{"s1":"s1", "s2":"s2", "s3":"s3"}`), the `x.get("s2", "s4")` method call would look for the key `"s2"`. Since `"s2"` exists in the dictionary, its corresponding value, which would be `"s2"`, is returned and printed.
The `get()` method retrieves a single value associated with a key, or a default if the key is not found; it does not return all keys or values.
The key `"s3"` is present, but `get()` is specifically looking for `"s2"`, so `"s3"` would not be the direct result.
Concept tested: Python dictionary get() method
Source: https://docs.python.org/3/library/stdtypes.html#dict.get
Topics
Community Discussion
No community discussion yet for this question.