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#

Just like with lists, the in operator searches 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’:

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

You can reverse the match with not. For example:

'Lion' not in animals

Type in one example from above:

[ ]:

Did it do what you expect?

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:

[ ]: