PCEP-30-02 · Question #57
What is the expected output of the following code? x = {(1, 2): 1, (2, 3): 2} print(x[(1, 2)])
The correct answer is D. 1. D is correct because x[(1, 2)] performs a dictionary lookup using the tuple (1, 2) as a key, and that key maps to the integer value 1 - so print(x[(1, 2)]) outputs just 1. Why the distractors fail: A (2, 3): 2 is a key-value pair from the dictionary literal, not what a lookup…
Question
Options
- A(2, 3): 2
- B(1, 2): 1
- CThe code is erroneous.
- D1
How the community answered
(34 responses)- A3% (1)
- B12% (4)
- C9% (3)
- D76% (26)
Explanation
D is correct because x[(1, 2)] performs a dictionary lookup using the tuple (1, 2) as a key, and that key maps to the integer value 1 - so print(x[(1, 2)]) outputs just 1.
Why the distractors fail:
- A
(2, 3): 2is a key-value pair from the dictionary literal, not what a lookup returns - Python doesn't print pairs on access. - B
(1, 2): 1makes the same mistake: it confuses the entire key-value entry with the result of indexing. - C is wrong because tuples are valid dictionary keys in Python - they're immutable and therefore hashable, unlike lists.
Memory tip: Think of a dictionary like a filing cabinet - x[key] opens the drawer labeled key and hands you only the contents, not the label itself. The label (1, 2) stays on the drawer; 1 is what's inside.
Community Discussion
No community discussion yet for this question.