Comprehensions & Generators · Question 15 · Medium
A dictionary comprehension swaps keys and values of a price list in which two snacks cost the same. What is printed?
prices = {"chai": 10, "samosa": 15, "vada": 15}
print({v: k for k, v in prices.items()})
- {10: 'chai', 15: 'vada'}
- {10: 'chai', 15: 'samosa'}
- {10: 'chai', 15: ['samosa', 'vada']}
- KeyError
Answer and explanation
Answer: A. {10: 'chai', 15: 'vada'}
Explanation: Keys in a dictionary are unique. Both samosa and vada try to use the key 15, and the later assignment (vada) overwrites the earlier one without any error.
Previous: Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x… · Next: The generator function below contains print calls around its yield. In what…
Practise comprehensions & generators
Try a fresh set of comprehensions & generators questions with an explanation after every answer, free and without signing up: Comprehensions & Generators practice. Or sit a full placement mock test.
More comprehensions & generators questions
- filter is called with None as its function on a list of mixed values. Which…
- A comprehension walks through a list of rows and keeps only the odd values…
- Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x…
- The generator function below contains print calls around its yield. In what…
- A list comprehension uses a loop variable with the same name as a module-level…
- The in operator is used twice on the same generator before it is turned into a…
- A nested list comprehension is applied to a 2 × 3 matrix. What does it produce?
- The name arr is rebound to a new list after a generator expression is created…
More python practice
Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge