Start learning free

LESSON 231 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in Go: Swapping Keys and Values

Practice Read the full explanation

Given a map d whose keys and values are strings, return a new map 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 map 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

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Go, explained

    Problem overview

    The function invertDictionary takes a map[string]string named d and returns a new map with keys and values swapped. Each value of d becomes a key, mapping to the key it came from. The values of d are all different, so the result has as many entries as d.

    For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is map[purple:plum red:apple yellow:banana].

    Approach: one pass, one flipped assignment per entry

    Each entry turns around independently of the others, so one loop over d is enough. The flipped pairs go into a new map rather than into d. Adding and removing entries in a map while ranging over it is allowed in Go, but it makes it hard to know which entries the loop still has to visit, and a new map keeps the input untouched.

    Step by step

    1. Create result, an empty map[string]string{}.
    2. Range over d. for key, value := range d gives every entry as a key and its value.
    3. Store the swapped pair. result[value] = key makes the old value the new key.
    4. Return result.

    Why nothing is lost

    A map can hold only one value per key. When swapping, two entries of d would collide if they had the same value, because both would write to the same new key. The lesson promises that all values are different, so every write lands on a fresh key: the three-entry map in the first example gives a three-entry result, and a len check on both maps prints 3 and 3. The inverted map has exactly as many entries as the original.

    The solution in Go

    func invertDictionary(d map[string]string) map[string]string {
        result := map[string]string{}
        for key, value := range d {
            result[value] = key
        }
        return result
    }
    

    Go details worth knowing

    • Both variables of range. Over a slice, range yields an index and an element; over a map, it yields a key and a value. Both names are used here, so there is no _.
    • Visiting order is random. The loop may visit the entries in a different order on each run. That doesn't matter here, because each entry is written under its own key, and the problem says the order of the result doesn't matter.
    • Printing. fmt.Println prints maps sorted by key, so the output looks the same on each run.
    • Value types as keys. The values become keys, so they must be of a type that can be a map key. Strings can. A slice, for example, couldn't be used as a key at all.

    Edge cases and common mistakes

    • A word that is both a key and a value. For {"a": "b", "b": "c"} the result is map[b:a c:b]. The "b" appears twice in d, once as a value and once as a key, and in the result it has one entry: the one made from "a": "b". The entry "b": "c" makes the key "c". Because the result is a separate map, there is no mix-up.
    • One entry. {"cat": "dog"} gives map[dog:cat].
    • Repeated values. If two keys shared a value, both would write to the same new key, and one of them would be lost. Which one survives depends on the random visiting order. The lesson promises distinct values, so the result keeps every entry.
    • Swapping in place. Writing the swapped pairs into d while ranging over it would mix old and new entries. Use a new map.

    Testing

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