Functions and Classes in Python

Dictionaries

Overview:

  • Teaching: 10 min
  • Exercises: 10 min

Questions

  • What is a dictionary?
  • Why wouldn't I just use a list?
  • How do I access the items in a dictionary?
  • How do I modify or add items to a dictionary?

Objectives

  • Learn how to define, access, modify and add to dictionaries
  • Understand the difference between a dictionary

Dictionaries are another type of Python container. Instead of storing values by index, they store them associated with a key.

You create dictionaries using curly brackets, assiging values to their keys using a colon, e.g.

a = { "cat" : "mieow", "dog" : "woof", "horse" : "neigh" }
In [1]:
a = { "cat" : "mieow", "dog" : "woof", "horse" : "neigh"}
In [2]:
a
Out[2]:
{'cat': 'mieow', 'dog': 'woof', 'horse': 'neigh'}

You can look up values in the dictionary by placing the key in square brackets. For example, we can look up the value associated with the key "cat" using a["cat"].

In [3]:
a["cat"]
Out[3]:
'mieow'

What happens if the key does not exist?

In [4]:
a['fish']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-4-afabe6ae7883> in <module>
----> 1 a['fish']

KeyError: 'fish'

You insert items into the dictionary by assigning values to keys, e.g.

In [5]:
a["fish"] = "bubble"
In [6]:
a
Out[6]:
{'cat': 'mieow', 'dog': 'woof', 'horse': 'neigh', 'fish': 'bubble'}

You can list all of the keys or values of a dictionary using the keys or values functions (which you can find using tab completion and Python help)

In [7]:
help(a.values)
Help on built-in function values:

values(...) method of builtins.dict instance
    D.values() -> an object providing a view on D's values

In [8]:
a.keys()
Out[8]:
dict_keys(['cat', 'dog', 'horse', 'fish'])
In [9]:
a.values()
Out[9]:
dict_values(['mieow', 'woof', 'neigh', 'bubble'])

You can loop over the dictionary by looping over the keys and looking up the values in a for loop, e.g.

In [10]:
for key in a.keys():
    print("A %s goes %s" % (key, a[key]))
A cat goes mieow
A dog goes woof
A horse goes neigh
A fish goes bubble

You can put anything as a value into a dictionary, including other dictionaries and even lists. The keys should be either numbers or strings.

In [11]:
b = { "a" : ["aardvark", "anteater", "antelope"], "b" : ["badger", "beetle"], 26.5: a}

What do you think is at b["a"][-1]? What about b[26.5]["fish"]?

In [12]:
b[26.5]["fish"]
Out[12]:
'bubble'

Exercises

Below you have a dictionary that contains the full mapping of every letter to its Morse-code equivalent.

In [13]:
letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.',
                   'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--',
                   'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
                   'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
                   '0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
                   '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
                   ' ':'/' }

1

Use the Morse code dictionary to look up the Morse code for the letters "s" and "o". What is the Morse code for "SOS" (the international emergency distress signal)?

Solution

2

Here is a string that contains a message that must be converted to morse code. Write a loop that converts each letter into the morse code equivalent, and stores it into a list. Print the list out to see the full morse code message that must be sent. Note that you will need to use the .lower() function to get the lower case of capital letters.

In [15]:
message = "SOS We have hit an iceberg and need help quickly"

3

The inverted form of a dictionary is one where the keys are now looked up by value. For example, the below code inverts letter_to_morse such that the morse code is the key, and the letter is the value.

In [18]:
morse_to_letter = {}
for letter in letter_to_morse.keys():
    morse_to_letter[ letter_to_morse[letter] ] = letter

Check that this code works by verifying that morse_to_letter["..."] equals "s".

Next, loop through the morse code message you created in exercise 2 and see if you can convert it back to english. Note that you can join a list of letters together into a string using the code "".join(letters).

Solution

Key Points:

  • Python dicts are like Python lists, they can store anything!
  • Python dicts are different to Python lists in the way they are indexed. Lists are indexed with whole numbers, whereas dicts are indexed with some key, which can be anything. In many cases the key is a string.
  • An empty dict is created with my_dict = dict() or my_dict = {}.
  • We can explicitly construct a dict with my_dict = {'a' : 1, 'b' : 't', 'c' : False}.
  • We can access a value in a dict by using it's key my_dict['b'].
  • We can also easily add or change values in a dictionary: `my_dict['title'] = 'My personal dictionary'