Challenge - 5 Problems
Dictionary Inversion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of simple dictionary inversion
What is the output of this Python code that inverts a dictionary?
Python
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted)Attempts:
2 left
๐ก Hint
Think about swapping keys and values in the dictionary comprehension.
โ Incorrect
The dictionary comprehension swaps keys and values, so the output maps values to keys.
โ Predict Output
intermediate2:00remaining
Inverting dictionary with duplicate values
What is the output of this code that tries to invert a dictionary with duplicate values?
Python
original = {'a': 1, 'b': 2, 'c': 1}
inverted = {v: k for k, v in original.items()}
print(inverted)Attempts:
2 left
๐ก Hint
When keys repeat in a dictionary, the last one stays.
โ Incorrect
Since keys must be unique, the last key for value 1 ('c') overwrites the first ('a').
๐ง Debug
advanced2:00remaining
Identify the error in dictionary inversion code
What error does this code raise when trying to invert a dictionary?
Python
original = {'a': [1, 2], 'b': [3, 4]}
inverted = {v: k for k, v in original.items()}
print(inverted)Attempts:
2 left
๐ก Hint
Dictionary keys must be immutable types.
โ Incorrect
Lists are mutable and cannot be dictionary keys, so a TypeError is raised.
๐ง Conceptual
advanced1:30remaining
Number of items after inverting dictionary with unique values
If a dictionary has 5 unique keys and 5 unique values, how many items will the inverted dictionary have?
Attempts:
2 left
๐ก Hint
Inversion swaps keys and values one-to-one if all are unique.
โ Incorrect
Each unique key-value pair becomes a value-key pair, so the count stays the same.
โ Predict Output
expert2:30remaining
Output of inverting dictionary with tuple values
What is the output of this code that inverts a dictionary with tuple values?
Python
original = {'x': (1, 2), 'y': (3, 4)}
inverted = {v: k for k, v in original.items()}
print(inverted)Attempts:
2 left
๐ก Hint
Tuples are immutable and can be dictionary keys.
โ Incorrect
Tuples can be used as keys, so the inversion works and swaps keys and tuple values.