Dictionaries
If you want to create a pairwise connection between two data types, a dictionary {}
or dict()
is a good choice. Here, a key is linked to a value and can be read out via an index:
elemente = {}
elemente["H"] = "Hydrogen"
elemente["He"] = "Helium"
elemente["Li"] = "Lithium"
elemente["H"] # Results in "hydrogen"
The keys can be any data types as long as they are unchangeable. The values can be any data type.
a = dict()
a[(1,2,3)] = "with a tuple"
a[[1,2,3]] = "with a list" # TypeError: unhashable type: 'list'
There is a compact notation for initialisation:
elemente = {"H": "Hydrogen", "He": "Helium", "Li": "Lithium"}
If a value is reassigned, the old value is overwritten:
elemente = {"H": "Hydrogen", "He": "Helium", "Li": "Lithium"}
elemente["H"] = "Hydrogen"
Entries can also be easily removed again:
elemente = {"H": "Hydrogen", "He": "Helium", "Li": "Lithium"}
del elemente["H"]
The keys and values can also be read out as a kind of list:
elemente = {"H": "Hydrogen", "He": "Helium", "Li": "Lithium"}
elemente.keys() # Ergibt ["H", "He", "Li"]
elemente.values() # Ergibt ["Hydrogen", "Helium", "Lithium"]
It should be noted that there is no guarantee regarding the order, except that the keys and values are output in the same order if the dictionary has not been changed.