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()})
  1. {10: 'chai', 15: 'vada'}
  2. {10: 'chai', 15: 'samosa'}
  3. {10: 'chai', 15: ['samosa', 'vada']}
  4. 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

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