August 2018
Intermediate to advanced
366 pages
10h 14m
English
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') ...