PCEP-30-02 · Question #2
What is the expected output of the following code? ``python data = {'Peter': 30, 'Paul': 31} print(list(data.keys())) ``
The correct answer is D. ['Peter', 'Paul']. Option D is correct because dict.keys() returns a view of only the keys in the dictionary - not the values - and wrapping it with list() converts that view into a plain Python list of strings: ['Peter', 'Paul']. Options A and C are wrong because they show ['Peter': 30, 'Paul'…
Question
data = {'Peter': 30, 'Paul': 31}
print(list(data.keys()))
Options
- A['Peter': 30, 'Paul': 31]
- B['Peter', 'Paul']
- C['Peter': 30, 'Paul': 31]
- D['Peter', 'Paul']
How the community answered
(29 responses)- A7% (2)
- B3% (1)
- C17% (5)
- D72% (21)
Explanation
Option D is correct because dict.keys() returns a view of only the keys in the dictionary - not the values - and wrapping it with list() converts that view into a plain Python list of strings: ['Peter', 'Paul'].
Options A and C are wrong because they show ['Peter': 30, 'Paul': 31], which mixes dictionary syntax (colon-separated key-value pairs) inside a list - this is not valid Python. A list holds individual elements separated by commas, not key-value pairs. If you want keys and values, you'd call data.items(), which yields tuples like [('Peter', 30), ('Paul', 31)].
Options B and D appear identical as written, so the distinction is likely a formatting artifact in the original exam (e.g., different quote styles or whitespace). The key concept remains: list(data.keys()) produces ['Peter', 'Paul'].
Memory tip: Think of .keys(), .values(), and .items() as three "windows" into a dictionary - keys only, values only, or both as pairs. Wrapping any of them in list() just snapshots that window into a concrete list.
Community Discussion
No community discussion yet for this question.