In this lesson, you will learn how to swap keys and values in a dictionary while safely managing duplicate values using grouping techniques.
The Basic Inversion
At its simplest, inverting a dictionary means turning the values into keys and the keys into values. If every value in your original dictionary is unique, you can use a dictionary comprehension to flip them in one line:
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
# Result: {1: 'a', 2: 'b', 3: 'c'}
Handling Collisions
In real-world data, values are often not unique. If you have two different keys sharing the same value, a standard comprehension will overwrite the first key with the last one it encounters, leading to data loss. To avoid this, we want to group the original keys into a list under the new key.
Because we cannot easily "group" inside a standard dictionary comprehension, we use a loop pattern or dict.setdefault() to build the mapping:
data = {'apple': 'fruit', 'carrot': 'veg', 'banana': 'fruit'}
inverted = {}
for k, v in data.items():
# If the list doesn't exist for this value, create one; then append
inverted.setdefault(v, []).append(k)
# Result: {'fruit': ['apple', 'banana'], 'veg': ['carrot']}
Why Not Just a Comprehension?
You might be tempted to force this into a comprehension, but complex grouping logic often makes comprehensions unreadable and inefficient. While you can use nested loops or if conditions to filter data, dictionary comprehensions are best suited for 1-to-1 mappings. When you need to transform values into collections (like lists), a standard iterative loop is the idiomatic "Pythonic" way to maintain clarity and avoid complexity traps.
By understanding when a simple swap is sufficient and when you need to group items, you gain total control over your data structures.
Key Takeaway: Use a dictionary comprehension for simple 1-to-1 key-value swaps, but switch to a standard loop with setdefault() when multiple keys map to the same value to prevent data loss.