Start learning free

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

Invert a Dictionary in TypeScript: 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

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in TypeScript, explained

    Problem overview

    The method invertDictionary receives an object d with string keys and string values. It returns a new object with keys and values swapped: every value of d becomes a key, mapped to the key it belonged to. 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 {"red": "apple", "yellow": "banana", "purple": "plum"}. For {"cat": "dog"} it is {"dog": "cat"}.

    The third example is the interesting one: {"a": "b", "b": "c"} gives {"b": "a", "c": "b"}. The text "b" is a value in one entry and a key in another. That is fine, because the two roles are separate: the value "b" of the entry "a": "b" becomes a key mapping to "a", and the entry "b": "c" turns into "c": "b".

    Approach

    Build the answer in a new object and leave d alone. One pass over the entries of d is enough, since each entry turns around on its own. For each pair, store result[value] = key.

    To read the pairs you need both the key and the value of each entry. Object.entries(d) returns them as an array of two-item arrays, such as [["apple", "red"], ["banana", "yellow"]].

    On {"cat": "dog", "owl": "bird"}, Object.entries gives [["cat", "dog"], ["owl", "bird"]]. The first round stores result["dog"] = "cat" and the second stores result["bird"] = "owl", so the answer is {"dog": "cat", "bird": "owl"}. The guarantee that the values differ is what makes this safe: no two entries write to the same new key, so none is lost.

    Step by step

    1. Create the empty object. result is declared with const and the same type as d, { [key: string]: string }.
    2. Loop over the entries. for (const [key, value] of Object.entries(d)) unpacks each two-item array into the variables key and value.
    3. Store the swapped pair. result[value] = key makes the old value the new key.
    4. Return result after the loop.

    The solution in TypeScript

    class Solution {
        invertDictionary(d: { [key: string]: string }): { [key: string]: string } {
            const result: { [key: string]: string } = {};
            for (const [key, value] of Object.entries(d)) {
                result[value] = key;
            }
            return result;
        }
    }
    

    Details worth knowing:

    • Destructuring. const [key, value] takes the first item of the pair as key and the second as value. It is shorthand for reading entry[0] and entry[1].
    • Object.entries versus for...in. A for...in loop gives only the keys, so you would look each value up with d[key]. Object.entries hands you both at once.
    • The input is untouched. The loop only reads d and writes to result, so adding to result while looping is safe.
    • Keys are always strings. That suits this lesson, whose values are strings, so they work as keys directly.

    Inverting twice gives back the original object, as long as the values were all different. That makes a quick sanity check for your own tests: invertDictionary(invertDictionary(d)) should have the same entries as d.

    Edge cases and common mistakes

    • Repeated values. The lesson guarantees all values differ. If two did not, they would land on the same key and the later entry would win: {"a": "x", "b": "x"} gives {"x": "b"}, and "a" is lost.
    • Swapping inside d. Changing d while reading it is confusing and is not asked for. The method returns a new object.
    • Writing result[key] = value. That just copies d.
    • A word that is both key and value. The case {"a": "b", "b": "c"} works without special handling, because the result is a separate object.

    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 TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free