Dictionaries & Sets · Question 15 · Medium

pop() is called for a key that exists and for one that does not. What does this print?

d = {"a": 1, "b": 2}
x = d.pop("a")
y = d.pop("z", -1)
print(x, y, d)
  1. 1 -1 {'b': 2}
  2. 1 -1 {'a': 1, 'b': 2}
  3. 1 None {'b': 2}
  4. KeyError
Answer and explanation

Answer: A. 1 -1 {'b': 2}

Explanation: pop("a") removes the key a and returns its value 1. The key z is missing, but because a default is supplied pop returns -1 instead of raising KeyError. Only b is left.

Previous: Which of the following values can be used as a dictionary key? · Next: An int, a float and a bool are used as keys in one dictionary literal. What…

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