Most programming languages have a form of dictionary. They consist of key and item pairs. The key - typically, a str allows quick lookup of the item: for example, a list or int. In python a dictionary is refered to as a dict.

Creating a dict using static data#

The basic syntax to declare one statically is as follows:

foo = {'bar':10, 'spam':'eggs', 10:'knights'}

A few things to notice:

  • A dict uses {}

  • Key and item pairs are separated by a semi colon

  • The data type of the keys and items do not need to be consistent. It can be any type you require.

My recommendation is that you keep the data type for the key consistent. This simplification avoids silly mistakes. Flexibility isn’t always your friend!

We access the items in the dict by using their keys


Creating an empty dict and adding key:items#

This is an easy operation. First we simply create a dict with no key item pairs and assign to a variable.

{'bar': 10, 'spam': 'eggs', 10: 'knights'}
<class 'dict'>

To add an item we use a simple syntax where we specify the key between [] and assign the item value

foo = {}
foo['bar'] = 'spam'
foo['eggs'] = 10.0
{'bar': 'spam', 'eggs': 10.0}

Checking for the existance of a key#

Keys must be exist in a dict to be referenced You will raise an exception if you try reference a key that is not present. If you want to check if a key exists you can use the following syntax:

foo = {}
foo['spam'] = 'eggs'

if 'spam' in foo:
    print('oh dear there is no spam')

Dictionary comprehensions#

If needed you can also create a dict using a dictionary comprehension e.g.

keys = ['bar', 'spam', 'nee']
items = [10, 'eggs', 'knights']

foo = {key:item for key, item in zip(keys, items)}
{'bar': 10, 'spam': 'eggs', 'nee': 'knights'}

Nested dictionaries#

Sometimes it can be useful to have a nested dictionary. A good example of when this is useful is when creating a pandas Dataframe. You can think of a nested dictionary as having a table like structure. Here’s a simple example:

bands_dict = {'band': {0: 'pantera', 1: 'metallica', 2: 'megadeth', 3: 'anthrax'},
              'n_albums': {0: 9, 1: 10, 2: 15, 3: 11},
              'yr_formed': {0: 1981, 1: 1981, 2: 1983, 3: 1981},
              'active': {0: False, 1: True, 2: True, 3: True}}

The variable bands_dict is just a simple dict. However, each key can be though of as a column name in a table. Each item contains the row data. For example to find the data in row 0 of the bands column we use:


Or if you want all data in a column you simple use the key:

{0: 1981, 1: 1981, 2: 1983, 3: 1981}

Again this data structure might be useful to create if you are collecting data during the run of a model of algorithm.