0
0
Pythonprogramming~5 mins

Inverting a dictionary in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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:
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?
AIt will raise an error
BSome keys will be lost because dictionary keys must be unique
CThe dictionary will keep all keys and values as is
DThe dictionary will become empty
Which Python method helps to iterate over key-value pairs in a dictionary?
Aitems()
Bkeys()
Cvalues()
Dget()
What is the output of this code?
original = {'x': 10, 'y': 20}
inverted = {v: k for k, v in original.items()}
print(inverted)
A{'x': 10, 'y': 20}
B{'10': 'x', '20': 'y'}
C{10: 'x', 20: 'y'}
DError
How can you invert a dictionary and keep all original keys if values are duplicated?
AUse keys() method only
BUse a simple comprehension
CIgnore duplicates
DMap each value to a list of keys
What type of Python object is created when you invert a dictionary?
AAnother dictionary
BA list
CA set
DA tuple
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.