Dictionaries
Dictionaries are a data structure used to arbitrarily map keys with values. The lists, which we have already seen above, can be thought of as dictionaries in which the keys are a sequence of integers, where a number corresponds to each number (index).
key -> value
Per le liste
list[0] -> 1
list[1] -> "house"
...
The dictionaries, however, have a more general aspect because the keys can assume any value and is often a string whose content has an indicative purpose of the value it contains (very similar to the name of a variable). In Python, dictionaries are recognized because they are collected within curly brackets {} in which key-value pairs are defined separated by a comma.
dictionaryname = { key1 : value1, key2: value2, … }
For example:
price = { "key": 12, "door": 24, "lock": 18 }
print(prezzo["key"])
if you run it, you get:
>>>
12
As we can see, to access the values of the dictionary it is sufficient to write the name of the dictionary and then to index the key.
dictionaryname[key]
If you search for a key that is not in a dictionary, you get an exception called KeyError. To define an empty dictionary is defined
dictionaryname = {}
The keys that can be defined within a dictionary are immutable, ie once defined they can not change their name, while their corresponding value can vary freely.