Dictionaries

Dictionaries are the best! Their syntax is similar to a list and, like a list, a dictionary holds any number of values. Dictionaries are different, however, because instead of holding values at index locations dictionaries use keys. Imagine you wanted to store a collection of scientific names of animals. You would like to retrieve the scientific name of an animal using it’s common name. In other words, if you type “Lion” into your search tool it gives you “Panthera Leo” as a result. A dictionary is exactly what you need. Think of a dictionary like this:

Image of a Python Dictionary

In the drawing the common name of an animal is the key and the scientific name is the value. In this lecture you’ll learn how to create change and use dictionaries.

Create a Dictionary

Dictionaries are declared with key/value pairs separated by colons. Here’s an example:

animals = { 'Lion': 'Panthera Leo',
           'Tiger': 'Panthera Tigris',
           'Bear': 'Ursus Arctos',
          }

In the example above I separated the animals onto different lines to make it more readable. It’s just as valid to do it all on one line like this:

animals = {'Lion': 'Panthera Leo', 'Tiger': 'Panthera Tigris', 'Bear': 'Ursus Arctos',}

Pick your favorite example and type it into the next cell:

[ ]:

Just like a list, a dictionary can be empty. Here’s how you create an empty dictionary:

animals = {}

Dictionaries are their own type in Python. Here’s how you use the type function to discover what type a dictionary is:

print(type(animals))

Try it:

[ ]:

Access, Add and Remove Dictionary Elements

Dictionaries are accessed just like lists but with keys between the [ and ] brackets. For example:

print(animals['Lion'])
print(animals['Tiger'])
print(animals['Bear'])

Use the print function to access one of the animals in the animals dictionary:

[ ]:

Dictionary elements are created at any time. For example, we here’s how you create an element to hold the scientific name of the common house cat:

animals['Cat'] = 'Felis Silvestris Silvesteris'

Dictionary elements are reassigned when they appear on the left of the equal sign:

animals['Bear'] = 'Ursus Arctos Horribilis' # Grizzly Bear

Dictionary elements can be deleted with the del operator, just like with a list.

del animals['Lion']

The clear function remove all of the elements of a dictionary:

animals.clear()

Practice adding, changing and removing items from the animals dictionary:

[ ]:

Dictionary Length

Just like with lists the len operator tells you how many key/value pairs are in a dictionary.

animals = { 'Lion': 'Panthera Leo', 'Tiger': 'Panthera Tigris', 'Bear': 'Ursus Arctos'}
print(len(animals))

Enter the example code into the next cell:

[ ]:

Can you guess what the length is?

Searching for Keys with in

The in operator works on dictionaries. It looks through the keys for one that matches. For example you can check to see if your animals dictionary contains an entry for ‘Lion’:

if 'Lion' in animals:
    print ('There are Lions here!')

You can reverse the match with not. For example:

if 'Lemur' not in animals:
    print ('No Lemurs')

Type in one example from above:

[ ]:

Did it do what you expect?

Iterating Through Dictionaries with for

A dictionary can be three related sequences when used with a for loop:

  1. A sequence of values

  2. A sequence of keys

  3. A sequence of key/value pairs

You should know how to construct a for loop for each of the sequences that a dictionary provides. The simplest (and most useful) form is a sequence of keys. Here’s an example:

for key in animals:
    print ("Common name:", key)

The nice thing about iterating over keys is that you have easy access to the value as well. Let’s update the previous example to print both key and value for each animal:

for key in animals:
    print ("Common name:", key, "Scientific name:", animals[key])

Try the updated exmple in the next cell:

[ ]:

If you don’t care about keys you can iterate over a colletion of values:

for value in animals.values():
    print("Scientific name:", value)

Try that in the next cell:

[ ]:

What if you wanted keys? It’s not easy to get a key from a value, so the for loop in the previous example doesn’t have a good way to print the common name. That’s a bit of a limitation. The final form iterates over key value pairs:

for key, value in animals.items():
    print ("Common name:", key, "Scientific name:", value)

Notice how there are two loop variables separated by commas! A sequence can produce pairs of itms (like the items function). When they do you need two variables. Type in the example into the next cell:

[ ]:

Try to memorize the three for loops that iterate over a dictionary. Start with the first one, it’s the most used.

Key Errors

If you access a key that doesn’t exist you get a KeyError exception.

print (animals['Sloth'])

Try the example to see the error:

[ ]:

An exception halts your program unless you handle it. To avoid a crash it’s common to check that a key exists before using it to guard against an exception. For example:

if 'Sloth' in animals:
    print ('Sloths are:', animals['Sloth'])
else:
    print ("I don't know about Sloths")

Dictionaries provide the get() function that will never cause an exception.

print(animals.get('Sloth'))

The get function returns None if the key doesn’t exist in the dictionary. Try using get in the next cell:

[ ]: