Learn how Python dictionaries store key-value pairs and how to access tuple elements within dictionary values. Understand the output of this code example for the Python Institute PCEP-30-02 certification exam.
Table of Contents
Question
What is the output of the following snippet?
dct = {} dct['1'] = (1, 2) dct['2'] = (2, 1) for x in dct.keys(): print(dct[x][1], end='')
A. 12
B. (2, 1)
C. (1, 2)
D. 21
Answer
D. 21
Explanation
This code snippet creates an empty dictionary `dct`, then adds two key-value pairs to it:
- The key ‘1’ maps to the tuple value (1, 2)
- The key ‘2’ maps to the tuple value (2, 1)
The `for` loop iterates through each key in `dct.keys()`, which are the strings ‘1’ and ‘2’.
For each key `x`, it accesses the dictionary value `dct[x]`, which is a tuple. It then indexes into the tuple using `[1]` to get the second element of each tuple.
So on the first iteration, `x` is ‘1’, `dct[x]` is (1, 2), and `dct[x][1]` is 2.
On the second iteration, `x` is ‘2’, `dct[x]` is (2, 1), and `dct[x][1]` is 1.
The `print()` statement prints out each of these second tuple elements, with `end=”` specifying to not print a newline between the elements.
Therefore, the code prints out: 21
So the correct answer is D. 21
Python Institute PCEP-30-02 certification exam practice question and answer (Q&A) dump with detail explanation and reference available free, helpful to pass the Python Institute PCEP-30-02 exam and earn Python Institute PCEP-30-02 certification.