What is the output of the following Python code snippet?

x = {1: 'a', 2: 'b'}
y = x.get(3, 'default')
print(y)

Answer and explanation

Correct answer: A. 'default'

  1. Step 1: Analyze the dictionary `.get(key, default)` method behavior.
  2. Step 2: Key 3 does not exist in `x`. Instead of raising a KeyError, `.get()` returns the specified fallback argument `'default'`.
Answer
'default'.
Why not the others: KeyError is raised by direct index notation `x[3]`, not `.get()`; None is returned if no fallback is provided; 3 is the queried key.

Practise more Algorithms and Python Programming.

Free questions with an explanation for every one, and full timed EmSAT Achieve (UAE) mock tests.