Start learning free

LESSON 232 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in Swift: Swapping Keys and Values

Practice Read the full explanation

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

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Swift, explained

    Problem overview

    The function invertDictionary receives a dictionary d whose keys and values are strings. It returns a new dictionary with keys and values swapped: every value of d becomes a key that maps back 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 maps "red" to "apple", "yellow" to "banana" and "purple" to "plum".

    Approach: turn each entry around

    Every entry can be reversed on its own, with no need to look at the others. One pass over d is enough: for each pair, store the key under the value. Because the values are all different, no two entries are written to the same key and nothing gets lost.

    A key that is also a value does no harm. In ["a": "b", "b": "c"], "b" is a value of the first entry and a key of the second. The first entry becomes "b": "a", the second becomes "c": "b", and the two don't interfere, since the result is a separate dictionary.

    Step by step

    1. Create result as an empty [String: String] with var.
    2. Loop over the entries with for (key, value) in d.
    3. Store the swapped pair: result[value] = key.
    4. Return result.

    For ["a": "b", "b": "c"], the loop meets the entry ("a", "b") and sets result["b"] = "a". It meets ("b", "c") and sets result["c"] = "b". The loop may visit them in either order, and the result is the same: "b" maps to "a" and "c" maps to "b".

    The idea is useful when you have a lookup in one direction and need the other: from a name to a color, then from a color back to its name. It only works cleanly when the values are unique, because each value becomes a key and keys are unique.

    The solution in Swift

    class Solution {
        func invertDictionary(_ d: [String: String]) -> [String: String] {
            var result = [String: String]()
            for (key, value) in d {
                result[value] = key
            }
            return result
        }
    }
    

    Swift details

    • Tuple pattern. A for-in loop over a dictionary produces each entry as a key-value pair. The pattern (key, value) splits the pair into two constants.
    • A new dictionary. Dictionaries are value types. d is never changed, and result is a separate dictionary that the function returns.
    • Order is not defined. The loop may visit the entries of d in any order, and the result's entries can print in any order. Since each entry lands under its own key, the final content is the same either way.

    Edge cases and common mistakes

    • A single entry. ["cat": "dog"] gives ["dog": "cat"].
    • Duplicate values. If two keys shared a value, such as ["a": "x", "b": "x"], the swapped keys would collide: both write to the key "x", the later write replaces the earlier, and the result has 1 entry instead of 2. Which one survives depends on the order the loop meets them in, and that order isn't defined for a dictionary. The lesson guarantees distinct values, so this doesn't happen in its tests.
    • Swapping the wrong way. result[key] = value copies the dictionary instead of inverting it.

    Testing

    Entries are listed in alphabetical order here for readability.

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