Dictionaries & Sets · Question 9 · Medium

setdefault() is called twice with the same key. What does the dictionary look like at the end?

d = {}
d.setdefault("k", []).append(1)
d.setdefault("k", []).append(2)
print(d)
  1. {'k': [2]}
  2. {'k': [1]}
  3. {'k': [1, 2]}
  4. {'k': [[1], [2]]}
Answer and explanation

Answer: C. {'k': [1, 2]}

Explanation: The first call finds no key k, stores the empty list and returns it, and 1 is appended. The second call finds k already present and returns the same stored list, so 2 is appended to it.

Previous: A key is added and an existing key is updated before the keys are listed. What… · Next: A list is used as a dictionary key. What happens when this runs?

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