Dictionaries & Sets · Question 19 · Hard
A keys view is taken before the dictionary is changed. What does this print?
d = {"x": 1}
ks = d.keys()
d["y"] = 2
d.update({"x": 5, "z": 3})
print(len(ks), d["x"])
- 1 5
- 3 5
- 3 1
- 1 1
Answer and explanation
Answer: B. 3 5
Explanation: keys() returns a live view, not a copy, so it reflects keys added later: x, y and z make 3. update() overwrites the value of the existing key x with 5 and adds z.
Previous: New keys are added to a dictionary inside a for loop over the same dictionary… · Next: A grade dictionary is inverted with a comprehension. What 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
- An int, a float and a bool are used as keys in one dictionary literal. What…
- Sets are built from the letters of two words. What is printed?
- New keys are added to a dictionary inside a for loop over the same dictionary…
- A grade dictionary is inverted with a comprehension. What is printed?
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