Inverting a dictionary means swapping its keys and values. This helps when you want to look up original keys by their values.
Inverting a dictionary in Python
Start learning this pattern below
Jump into concepts and practice - no test required
inverted_dict = {value: key for key, value in original_dict.items()}This creates a new dictionary where each original value becomes a key, and each original key becomes a value.
Make sure original values are unique and hashable, or you may lose data or get errors.
original = {'a': 1, 'b': 2}
inverted = {v: k for k, v in original.items()}
print(inverted)original = {'apple': 'fruit', 'carrot': 'vegetable'}
inverted = {v: k for k, v in original.items()}
print(inverted)original = {'x': 10, 'y': 10}
inverted = {v: k for k, v in original.items()}
print(inverted)This program inverts a color-to-hex dictionary so you can find the color name by its hex code.
original_dict = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
inverted_dict = {value: key for key, value in original_dict.items()}
print('Original:', original_dict)
print('Inverted:', inverted_dict)If original values are not unique, some keys will be lost in the inverted dictionary.
Values must be hashable (like strings, numbers, or tuples) to be dictionary keys.
Inverting swaps keys and values in a dictionary.
Use dictionary comprehension with .items() to invert.
Be careful with duplicate values and unhashable types.
Practice
What does inverting a dictionary mean in Python?
Solution
Step 1: Understand dictionary structure
A dictionary has keys and values paired together.Step 2: Define inverting
Inverting means swapping each key with its value, so keys become values and values become keys.Final Answer:
Swapping keys and values so values become keys and keys become values -> Option BQuick Check:
Inverting = swapping keys and values [OK]
- Thinking inverting sorts the dictionary
- Confusing inverting with removing duplicates
- Assuming values become uppercase strings
Which of the following is the correct syntax to invert a dictionary d using dictionary comprehension?
Solution
Step 1: Recall dictionary comprehension syntax
It uses {new_key: new_value for key, value in dict.items()}.Step 2: Swap keys and values correctly
To invert, new_key = value and new_value = key, so use {v: k for k, v in d.items()}.Final Answer:
{v: k for k, v in d.items()} -> Option DQuick Check:
Correct syntax = {v: k for k, v in d.items()} [OK]
- Swapping variables incorrectly in comprehension
- Using d[v] or d[k] inside comprehension wrongly
- Forgetting to call .items() on dictionary
What is the output of this code?
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted)Solution
Step 1: Understand original dictionary
Keys are 'a', 'b', 'c' and values are 1, 2, 3.Step 2: Invert dictionary using comprehension
Swapping keys and values gives keys 1, 2, 3 and values 'a', 'b', 'c'.Final Answer:
{1: 'a', 2: 'b', 3: 'c'} -> Option AQuick Check:
Inverted dict = {1: 'a', 2: 'b', 3: 'c'} [OK]
- Expecting original dictionary output
- Confusing string and integer keys
- Thinking inversion causes error here
What is wrong with this code to invert a dictionary?
d = {'x': 10, 'y': 10}
inverted = {v: k for k, v in d.items()}
print(inverted)Solution
Step 1: Identify duplicate values in dictionary
Both 'x' and 'y' have value 10, which is duplicated.Step 2: Understand dictionary key uniqueness
When inverting, keys must be unique, so only one key-value pair with key 10 remains.Final Answer:
It will keep only one key for duplicate values -> Option AQuick Check:
Duplicate values cause lost keys in inversion [OK]
- Expecting all keys preserved after inversion
- Thinking it raises an error for duplicates
- Ignoring key uniqueness in dictionaries
Given a dictionary with possible duplicate values, how can you invert it so each value maps to a list of keys that had that value?
original = {'a': 1, 'b': 2, 'c': 1}Which code correctly inverts it to
{1: ['a', 'c'], 2: ['b']}?Solution
Step 1: Understand problem with duplicates
Simple inversion loses keys when values repeat, so we need lists to hold multiple keys.Step 2: Use setdefault and append to collect keys
Loop through items, for each value use setdefault to create list if missing, then append key.Step 3: Check code correctness
inverted = {} for k, v in original.items(): inverted.setdefault(v, []).append(k) uses this approach correctly, building lists of keys per value.Final Answer:
inverted = {} for k, v in original.items(): inverted.setdefault(v, []).append(k) -> Option CQuick Check:
Use setdefault + append to group keys by value [OK]
- Using simple comprehension losing duplicate keys
- Swapping variables incorrectly in comprehension
- Expecting one-to-one inversion with duplicates
