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
- Create an empty dictionary named
result. The swapped pairs go here whiledstays as it is. - Loop over the entries with
for key, value in d.items(). After each pass,keyandvaluehold the two halves of one entry. - Store the swapped pair:
result[value] = key. The old value is now the key, and the old key is the stored value. - Return
resultafter 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 dvisits the keys. To get the values as well, used.items(), which gives pairs, or look each value up withd[key]. - Unpacking.
for key, value in d.items()is the same as taking each pair, such as('apple', 'red'), and assigning its first part tokeyand its second tovalue. - 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
TypeErrorwhen 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
dwhile looping over it. Adding or removing keys of a dictionary during a loop over it raises aRuntimeError. 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'}.
