nerdexam
Python_Institute

PCEP-30-02 · Question #56

What is the expected output of the following code? data = {'z': 23, 'x': 7, 'y': 42} for _ in sorted(data): print(data[_], end=' ')

The correct answer is B. 74223. Option B is correct because sorted(data) iterates over the dictionary's keys in alphabetical order - producing ['x', 'y', 'z'] - and then data[_] looks up the corresponding values: x→7, y→42, z→23, printing 7 42 23. Option A (72342) is a trap for those who think sorted(data)…

Question

What is the expected output of the following code? data = {'z': 23, 'x': 7, 'y': 42} for _ in sorted(data): print(data[_], end=' ')

Options

  • A72342
  • B74223
  • C42237

How the community answered

(38 responses)
  • A
    16% (6)
  • B
    79% (30)
  • C
    5% (2)

Explanation

Option B is correct because sorted(data) iterates over the dictionary's keys in alphabetical order - producing ['x', 'y', 'z'] - and then data[_] looks up the corresponding values: x→7, y→42, z→23, printing 7 42 23.

Option A (72342) is a trap for those who think sorted(data) sorts the values in ascending order (7, 23, 42), but sorted() on a dict always operates on keys, not values. Option C (42237) would result from mistakenly assuming sorted(data) sorts by value in descending order (42, 23, 7), which is also wrong for the same reason.

Memory tip: Think of a dictionary as a filing cabinet - sorted(data) alphabetizes the file tab labels (keys), not the contents inside (values). If you want sorted values, you'd need sorted(data.values()).

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice