Dictionaries

Resources

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:

flowchart LR
    subgraph values
    John
    Ringo
    Paul
    George
    end
    subgraph indexes
    0
    1
    2
    3
    end
    0 --> John
    1 --> Ringo
    2 --> Paul
    3 --> George

A dictionary:

flowchart LR
    subgraph values
    Ringo
    Starr
    drums
    end
    subgraph keys
    name
    surname
    instrument
    end
    name --> Ringo
    surname --> Starr
    instrument --> drums

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.

Note

Remember that you can use the min function to get the minimum value of a list or of an iterator.

Tip

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.

Tip

Alternatively this could be done using the zip function.

Create a dictionary that holds the complementary DNA nucleotides and use it to create a reverse and complementary DNA sequence.

Tip

Dicts and lists can hold other compound objets

Print the name and age of these two students.

Tip

Change the name of the gene2 from BRCA to BRCA2:

Tip

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.