Recall & Review
beginner
What does it mean to invert a dictionary?
Inverting a dictionary means swapping its keys and values. The original keys become values, and the original values become keys.
Click to reveal answer
beginner
How can you invert a dictionary in Python using a dictionary comprehension?
You can invert a dictionary by creating a new dictionary where each key-value pair is swapped:
inverted = {v: k for k, v in original.items()}Click to reveal answer
intermediate
What problem can occur if the original dictionary has duplicate values when inverting?
If the original dictionary has duplicate values, inverting it will lose data because keys in a dictionary must be unique. Only the last key for a duplicated value will be kept.
Click to reveal answer
beginner
Show a Python code example that inverts a dictionary and explain the output.
original = {'a': 1, 'b': 2, 'c': 3}Code:
Output:
Explanation: Each key-value pair is swapped, so 1 becomes a key with value 'a', and so on.
inverted = {v: k for k, v in original.items()}
print(inverted)Output:
{1: 'a', 2: 'b', 3: 'c'}Explanation: Each key-value pair is swapped, so 1 becomes a key with value 'a', and so on.
Click to reveal answer
intermediate
How can you invert a dictionary that has duplicate values without losing data?
You can invert it by making the values keys that map to a list of original keys:
inverted = {}
for k, v in original.items():
inverted.setdefault(v, []).append(k)Click to reveal answer
What happens if you invert a dictionary with duplicate values using a simple comprehension?
✗ Incorrect
When inverting, duplicate values become keys, but keys must be unique, so only the last key-value pair is kept.
Which Python method helps to iterate over key-value pairs in a dictionary?
✗ Incorrect
The items() method returns key-value pairs, which is useful for inverting dictionaries.
What is the output of this code?
original = {'x': 10, 'y': 20}
inverted = {v: k for k, v in original.items()}
print(inverted)✗ Incorrect
The dictionary is inverted by swapping keys and values.
How can you invert a dictionary and keep all original keys if values are duplicated?
✗ Incorrect
Mapping values to lists of keys preserves all keys even if values repeat.
What type of Python object is created when you invert a dictionary?
✗ Incorrect
Inverting a dictionary produces a new dictionary with keys and values swapped.
Explain how to invert a dictionary in Python and what issues might arise with duplicate values.
Think about how keys must be unique in dictionaries.
You got /4 concepts.
Write a Python code snippet to invert a dictionary that may have duplicate values, preserving all original keys.
Use a dictionary where each key maps to a list.
You got /4 concepts.