Dictionaries
Resources
- A Real Python introduction to dictionaries.
- Read about dictionaries, and more on dictionaries, in the official documentation.
Creation
Dictionaries, like lists, are compound types, they can hold several items. Lists are sequences, the elements that they hold are stored one after another, and we can access their items by their index, their position in the sequence.
Dictionaries also hold different values, but they are not ordered and, thus, we do not refer to them by their index. They are mappings, they assing a key to every value, and we use those keys to access to the values. In other languages these kind of objects are called hash tables, hash maps or associative arrays.
An example of a list:
A dictionary:
We create a dictionary using curly braces ({}), and we write the key and the value separated by a colon (:): {key1: value1, key2: value2}. In the previous example the keys were: “name”, “surname”, and “instrument”, and the values were: “Ringo”, “Starr”, and “drums”. As you have seen in the previous example, we can get the values stored in a dictionary by using square brackes: some_dictionary[key].
We can ask Python to give us the all keys and values of a dictionary.
Be aware that the methods keys and values return iterators, so to print lists we have to pass those iterators to the list function.
Given the following dictionary, find out which is the minimum age of a student.
We can also iterate through tuples of keys and values using the items method.
If we want to know how many items is the dictionary holding we use the len function.
We have two lists, one with values and another one with keys, create a dictionary using them.
Create a dictionary that holds the complementary DNA nucleotides and use it to create a reverse and complementary DNA sequence.
Dicts and lists can hold other compound objets
Print the name and age of these two students.
Change the name of the gene2 from BRCA to BRCA2:
dicts are mutable
Dictionaries, like lists, are mutable, we can add, modify or remove, items after their creation. For instance, we can create an empty dictionary and fill it with values later.
dict keys are unique
One very important aspect of a dictionary is that keys are unique. If we try to store two values under the same key, only one will remain.
key in dict
We can check if a key is stored in a dictionary by using the in operator.