0
0
Pythonprogramming~20 mins

Inverting a dictionary in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Inversion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
ATypeError
B{'a': 1, 'b': 2, 'c': 3}
C{'1': 'a', '2': 'b', '3': 'c'}
D{1: 'a', 2: 'b', 3: 'c'}
Attempts:
2 left
๐Ÿ’ก Hint
Think about swapping keys and values in the dictionary comprehension.
โ“ Predict Output
intermediate
2: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)
A{1: 'c', 2: 'b'}
BKeyError
C{'a': 1, 'b': 2, 'c': 1}
D{1: 'a', 2: 'b', 1: 'c'}
Attempts:
2 left
๐Ÿ’ก Hint
When keys repeat in a dictionary, the last one stays.
๐Ÿ”ง Debug
advanced
2: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)
ASyntaxError
BNo error, prints inverted dictionary
CTypeError
DKeyError
Attempts:
2 left
๐Ÿ’ก Hint
Dictionary keys must be immutable types.
๐Ÿง  Conceptual
advanced
1: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?
A10
B5
C0
DDepends on the values
Attempts:
2 left
๐Ÿ’ก Hint
Inversion swaps keys and values one-to-one if all are unique.
โ“ Predict Output
expert
2: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)
A{(1, 2): 'x', (3, 4): 'y'}
B{'x': (1, 2), 'y': (3, 4)}
CTypeError
D{'(1, 2)': 'x', '(3, 4)': 'y'}
Attempts:
2 left
๐Ÿ’ก Hint
Tuples are immutable and can be dictionary keys.