Dictionaries
Dictionaries are collections of data that are unordered, changeable and indexed. They are found within a set of curly brackets ‘{}’. Each key within a dictionary is separated by a colon and each each element in the dictionary is separated by a comma. An empty dictionary without any items is {}.
The purpose of defining a dictionary is to access the contents of the dictionary through the key. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. (tuples are immutable lists).
Example: In this example, we are defining a dictionary to link the three letter code of an amino acid to the single letter code. These act as key-value pairs.
dictionary = { 'Arg': 'R', # a key-value pair 'Ala': 'A', 'Lys': 'L', 'His': 'H', } print(dictionary)
- Using an if condition, we check for the presence of
Lys
in the dictionary. If it is present, the pair ofLys
is printed.