Start learning free

LESSON 227 OF 287 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Invert a Dictionary in Python: Swapping Keys and Values

Practice Read the full explanation

Given a dict d whose keys and values are strings, return a new dict with the keys and values swapped: every value of d becomes a key, and it maps to the key it belonged to.

The order of the entries in the dict you return doesn't matter.

Example 1:

Input: d = {"apple": "red", "banana": "yellow", "plum": "purple"}
Output: {"red": "apple", "yellow": "banana", "purple": "plum"}
Explanation: "apple" mapped to "red", so now "red" maps to "apple". The other two entries turn around the same way.

Example 2:

Input: d = {"cat": "dog"}
Output: {"dog": "cat"}
Explanation: One entry gives one entry, turned around.

Example 3:

Input: d = {"a": "b", "b": "c"}
Output: {"b": "a", "c": "b"}
Explanation: "b" is both a key and a value of d. As the value of "a", it becomes a key that maps to "a". As a key, its entry "b": "c" turns into "c": "b".

Rules:

  • d has at least one entry.
  • All the values of d are different, so the result has as many entries as d.
  • Keys and values are words without spaces.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Invert A Dictionary in Python, explained

    Problem overview

    The method invertDictionary receives a dictionary d whose keys and values are strings. It returns a new dictionary in which every value of d is a key, and it maps to the key it came from. All the values of d are different, so the result has as many entries as d.

    For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {'red': 'apple', 'yellow': 'banana', 'purple': 'plum'}. One entry, {"cat": "dog"}, gives {'dog': 'cat'}. A word can be both a key and a value: {"a": "b", "b": "c"} gives {'b': 'a', 'c': 'b'}. There, "b" is a value of the first entry, so it becomes a key that maps to "a", while the original entry "b": "c" turns into "c": "b".

    Approach: one pass, one swap per entry

    Each entry turns around independently of the others. So the plan is to go through the entries of d once, and for each pair store the swapped pair in a new dictionary. The original d is only read, never changed, which is why the result goes into a separate dictionary.

    To get both parts of every entry at once, the loop uses d.items(). It produces the key-value pairs one at a time, and writing for key, value in d.items() unpacks each pair into two variables.

    Step by step

    1. Create an empty dictionary named result. The swapped pairs go here while d stays as it is.
    2. Loop over the entries with for key, value in d.items(). After each pass, key and value hold the two halves of one entry.
    3. Store the swapped pair: result[value] = key. The old value is now the key, and the old key is the stored value.
    4. Return result after the loop.

    The solution in Python

    class Solution:
        def invertDictionary(self, d: Dict[str, str]) -> Dict[str, str]:
            result = {}
            for key, value in d.items():
                result[value] = key
            return result
    

    Details worth knowing:

    • Looping over a dictionary directly gives only keys. for key in d visits the keys. To get the values as well, use d.items(), which gives pairs, or look each value up with d[key].
    • Unpacking. for key, value in d.items() is the same as taking each pair, such as ('apple', 'red'), and assigning its first part to key and its second to value.
    • Values become keys, so they must be usable as keys. Strings are, which is why this works. A value that is a list would raise a TypeError when used as a key, since lists can't be dictionary keys.
    • The same job in one expression. A dictionary comprehension, {value: key for key, value in d.items()}, gives the same result.

    Edge cases and common mistakes

    • Repeated values lose entries. The lesson guarantees that the values are all different. If two keys shared a value, the later one would overwrite the earlier one. For {"a": "x", "b": "x"}, the function returns {'x': 'b'}, with one entry instead of two.
    • Writing result[key] = value. That copies the dictionary instead of inverting it.
    • Changing d while looping over it. Adding or removing keys of a dictionary during a loop over it raises a RuntimeError. Building a separate result avoids the problem.
    • A word on both sides. The {"a": "b", "b": "c"} example works without any special handling, because the swapped pairs go into a new dictionary and don't touch the original.

    Testing

    • {"apple": "red", "banana": "yellow", "plum": "purple"} gives {'red': 'apple', 'yellow': 'banana', 'purple': 'plum'}.
    • {"cat": "dog"} gives {'dog': 'cat'}.
    • {"a": "b", "b": "c"} gives {'b': 'a', 'c': 'b'}.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free