20  Dictionaries

Dictionaries are another way in which we can store multiple values in Python. Unlike lists, they are unordered (the order doesn’t matter), and instead each value is associated with a lookup key. This allows us to store values against something that describes that value being stored. Dictionaries are structured as key : value pairs.

Let’s create an example dictionary. We use curly brackets to denote dictionaries.

Tip

Notice that our keys (the bit on the left hand side of the colon) are strings.

However - the bits on the right of the colon - our values - can be anything! We could even use lists or other dictionaries.

Dictionaries are fine with a variety of types being used as values within a single dictionary object.

20.1 Getting values from dictionaries

To refer to a value in a dictionary, we just provide the key :

20.2 Updating values in dictionaries

We can also update the value of a key this way.

Tip

Note that when we have included the dictionary key inside the f string, we have used single quotation marks (i.e. ['name'] rather than ["name"]). This is because Python would otherwise match up the opening quotation mark of our f-string with the opening quotation mark of ["name"], which will cause chaos!

A good option is to always open your string with double quotes (") and then use a single quote/apostrophe (') inside your string. This will avoid any problems.

20.3 Adding new key-value pairs to dictionaries

We can add new key : value pairs in the same way :

20.4 Deleting key-value pairs from dictionaries

We can also delete ones we don’t need.