Python Dictionaries

Lists

So we're already familiar with the idea of lists (Python's arrays), the idea being there's a series of values in a list:

my_list = ['here', 'are', 'some', 'values']

And you can access anything in that list using its zero-based index:

the_word_some = my_list[2]

You could think about writing the list like so (not valid Python, I'm just illustrating a point!):

my_list = [0: 'here', 1: 'are', 2: 'some', 3: 'values']

In this situation, you can clearly see the index each value has associated with it. There is a data type which would let us do this properly in Python - the dictionary. In a dictionary these indexes are known as keys.

Dictionaries

Here is the valid Python syntax for the code above, using a dictionary:

my_list = {0: 'here', 1: 'are', 2: 'some', 3: 'values'}

All we had to do was switch out the square brackets for braces from my invalid example above; a dictionary is defined by braces.

Values can be accessed in the same way as before:

the_word_some = my_list[2] # This works because we have a *key* of 2 in our dictionary 

Here's the big advantage: these keys do not have to be numbers. They can be strings as well!

Taking our example from before (I've added some newlines to try and make it more readable):

1my_list = {
2  'zero': 'here', 
3  'one': 'are', 
4  'two': 'some', 
5  'three': 'values'
6}

We can now access our value like so:

the_word_some = my_list['two'] # We use the key 'two' here since this is now the key in our dictionary

Dictionaries allow you to add or update keys at any time:

my_list['two'] = 'many'
my_list['four'] = 'New value!'

Would result in:

1{
2  'zero': 'here', 
3  'one': 'are', 
4  'two': 'many', 
5  'three': 'values',
6  'four': 'New value!'
7}