The last data structure we will cover in this module is a dictionary. Dictionaries provide us with the ability to organize data in key-value pairs: while in lists and tuples we use an index to retrieve a value, in dictionaries we use a key.
To define a dictionary we enclose a sequence of comma-separated key: value
pairs in curly brackets:
trips = { "Madrid": 2, "Paris": 1, "Berlin": 7, "London": 1, }
Here we created a dictionary to store the number of times we visited european capitals. The keys in the dictionary are the cities "Madrid"
, "Paris"
, "London"
and "Madrid"
, while the values are 2
, 1
, 7
and 1
.
To retrieve a particular value from this dictionary, we use the corresponding key:
trips["Madrid"]
which returns the value 2
.
One thing to note is that dictionaries can store any type of value, but the keys under which they are stored must be hashable values. This typically means that:
x = (["a", "b"], 1)
is immutable, but it cannot be used as a key because contains a mutable value (the list ["a", "b"]
)In the previous example we used strings (e.g. "Madrid") as keys, but we can use any other hashable value. Here we use integers as keys:
visits = { 1: ["Paris", "London"], 2: ["Madrid"], 7: ["Berlin"], }
The dictionary above uses the number of visits as keys and the cities visited as values.