Dictionaries & Sets · Question 12 · Medium

A dictionary comprehension maps numbers to their squares. What is printed?

sq = {n: n * n for n in range(1, 4)}
print(sq)
  1. {0: 0, 1: 1, 2: 4, 3: 9}
  2. {1: 1, 2: 4, 3: 9}
  3. {1: 1, 2: 4, 3: 9, 4: 16}
  4. [1, 4, 9]
Answer and explanation

Answer: B. {1: 1, 2: 4, 3: 9}

Explanation: range(1, 4) gives 1, 2 and 3; 4 is excluded. Each number becomes a key and its square becomes the value.

Previous: Difference and symmetric difference of two sets are printed in sorted form… · Next: A loop over items() adds up only the marks above 70. What total is printed?

Practise dictionaries & sets

Try a fresh set of dictionaries & sets questions with an explanation after every answer, free and without signing up: Dictionaries & Sets practice. Or sit a full placement mock test.

More dictionaries & sets questions

More python practice

Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge