ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()})
  1. A. {'a': 1, 'b': 2}
  2. B. {1: 'a', 2: 'b'}
  3. C. {'1': 'a', '2': 'b'}
  4. D. KeyError

Correct answer: B. {1: 'a', 2: 'b'}

This comprehension swaps keys and values: the original values (1, 2) become the new dict's keys, and the original keys ('a','b') become the new values, giving {1: 'a', 2: 'b'}.

More Python Programming questions

Exams that ask this topic