Start learning free

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

Invert a Dictionary in C#: 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 5
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in C#, explained

    Problem overview

    The method InvertDictionary receives a Dictionary<string, string> named d and returns a new dictionary with 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 doesn't matter.

    For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {"red": "apple", "yellow": "banana", "purple": "plum"}. For {"cat": "dog"} it is {"dog": "cat"}. The case {"a": "b", "b": "c"} gives {"b": "a", "c": "b"}: the string "b" is a value in one entry and a key in another, and each entry turns around on its own, so there is no clash.

    The lesson guarantees that all values are different, so the result has exactly as many entries as d.

    Approach: turn each entry around

    Each entry is a pair: a key and its value. Swapping means writing the pair into a new dictionary the other way round. Go through every entry of d once, read the value, and store result[value] = key.

    The swapped pairs go into a new dictionary instead of changing d in place. Adding an entry to a dictionary while a loop goes over it throws an InvalidOperationException, and building a fresh result avoids the problem.

    On the first example, the loop reads "apple" with the value "red" and stores "red" with the value "apple". Then it does the same for "banana" and "plum". After three rounds the new dictionary has three entries, and d is exactly as it was.

    Step by step

    1. Create an empty Dictionary<string, string> named result. Both key and value types are string.
    2. Write a foreach loop with a string named key over d.Keys, the collection of the dictionary's keys.
    3. Read the value stored under the key, d[key], into a string named value. Turning an entry around needs both halves.
    4. Store the swapped pair with result[value] = key. The old value is now the key. Because the values are all different, no two entries land on the same key.
    5. Return result after the loop.

    The solution in C#

    class Solution {
        public Dictionary<string, string> InvertDictionary(Dictionary<string, string> d) {
            Dictionary<string, string> result = new Dictionary<string, string>();
            foreach (string key in d.Keys) {
                string value = d[key];
                result[value] = key;
            }
            return result;
        }
    }

    Details worth knowing:

    • d.Keys is a view of the keys, and d[key] is always safe inside this loop, because every key in it exists in d.
    • Assigning to a key that doesn't exist yet adds an entry, so result[value] = key needs no ContainsKey check.
    • A foreach (var pair in d) loop over the entries would also work, with pair.Key and pair.Value. The lesson's loop over d.Keys does the same job.

    Edge cases and common mistakes

    • Repeated values. If two keys shared a value, the later assignment would overwrite the earlier one and an entry would be lost. For {"a": "x", "b": "x"} the result is the single entry {"x": "b"}. The lesson rules this case out.
    • Changing d in the loop. Adding entries to d while looping over its keys throws an exception. Use a separate result.
    • A value that is also a key. The example {"a": "b", "b": "c"} works because d is never modified: the answer is built in another dictionary.
    • Swapped assignment. result[key] = value would just copy d.

    Testing

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