Dictionaries in Python are associative containers where keys are unique. A key can appear a single time and has exactly one value.
If we want to support multiple values per key, we can actually solve the need by saving list as the value of our key. This list can then contain all the values we want to keep around for that key:
>>> rd = {1: ['one', 'uno', 'un', 'ichi'],
... 2: ['two', 'due', 'deux', 'ni'],
... 3: ['three', 'tre', 'trois', 'san']}
>>> rd[2]
['two', 'due', 'deux', 'ni']
If we want to add a new translation to 2 (Spanish, for example), we would just have to append the entry:
>>> rd[2].append('dos')
>>> rd[2]
['two', 'due', 'deux', 'ni', 'dos']
The problem arises when we want to introduce a new key:
>>> rd[4].append('four')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 4
For key 4, no list exists, so there is nowhere we can append it. So, our snippet to automatically reverse the mapping can't be easily adapted to handle multiple values, as it would fail with key errors the first time it tries to insert a value:
>>> rd = {}
>>> for k,v in d.items():
... rd[v].append(k)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyError: 1
Checking for every single entry, whether it's already in the dictionary or not, and acting accordingly is not very convenient. While we can rely on the setdefault method of dictionaries to hide that check, we can get a far more elegant solution by using collections.defaultdict.