Introductory Programming in Python: Lesson 11
Dictionaries

[Prev: Tuples] [Course Outline] [Next: Strings in Depth]

What are dictionaries

Dictionaries in python are known in other languages by other names, including "associative arrays" and "mappings". The latter being perhaps the more explanatory term. Dictionaries are basically a set of mappings from a key to a value. Keys can be of any non-mutable type, and values can be of any type including other dictionaries, lists, or tuples. Dictionaries specify a set of key:value pairs, such that when the dictionary is subscripted using a key it contains, the value associated with that pair is returned.

Forming a Dictionary

Dictionaries are formed using curly braces ({ }), and providing a comma separated list of key:value pairs between the open and close braces.

Python 2.4.3 (#1, Oct	2 2006, 21:50:13) 
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {
... 0: "This is the value for key 0",
... 1: "This is the value for key 1",
... "3": "See how keys can also be strings",
... (4, 5): "Or even tuples",
... "and for fun": 7
... }
>>>

Here we have a new dictionary, which we have assigned to a variable 'a'. The dictionary contains five key:value pairs, each specified using the format <key> : <value> within a comma separated list within curly braces. Note how keys can be of multiple different types within the same dictionary. Key order is not guaranteed by python. Similarly values can be of any type, and types can be mixed within one dictionary. Also note the existence of the empty dictionary ...

>>> b = {}
>>>

Using Dictionaries

Presumably, the first thing we would want to be able to do after forming a dictionary is to manipulate the key:value pairs. We would want to be able to extract individual pairs by their key name, which we do by using the subscription operator <dictionary>[<expression>]

>>> a[0]
'This is the value for key 0'
>>> a["3"]
'See how keys can also be strings'
>>> a[4,5]
'Or even tuples'
>>>

In a similar way to lists we can change the contents of a dictionary, meaning dictionaries are mutable. Specifically, we can change the value of a certain key using the assignment statement <dictionary>[<expression>] = <expression>.

>>> a["3"] = "Told you keys could also be strings"
>>> a["3"]
'Told you keys could also be strings'
>>>

Similarly, a simple assignment statement can add a new key:value pair to a dictionary, as long as the key doesn't already exist in the dictionary. If the key does already exist, it's value is simply changed as in the assignment statement above.

>>> a["new"] = "a new pair has been added"
>>> a
{0: 'This is the value for key 0', 1: 'This is the value for key 1', '3': 'Told
you keys could also be strings', 'new': 'a new pair has been added', (4, 5): 'Or
even tuples'}
>>>

It is important to realise, that this implicit replacement of the values of already extant keys ensures that keys are unique. Also, note that attempting to access a key that doesn't exist causes an error...

>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 3
>>>

Which means that before we can add to the value of a particular key using an assignment such as
a["n"] = a["n"] + 1 we must first ensure the key exists to add to. The same is of course true of any operator applied to a key's value. The reason for this is that assignments evaluate the expression on the right of the equals before assigning it to the variable on the left, meaning the value of a["n"] would be looked up before it has been put into the dictionary, causing an error.

Entire dictionaries can be compared using the standard comparison operators. If 'a' and 'b' are both dictionaries

We can loop over the keys of a dictionary, using a for statement.

>>> for k in a:
...     print k
... 
0
1
3
new
(4, 5)
>>>

Or perhaps more usefully, we can loop over the keys, and use them as indexes into the dictionary.

>>> for k in a:
...     print k, ":", a[k]
... 
0 : This is the value for key 0
1 : This is the value for key 1
3 : Told you keys could also be strings
new : a new pair has been added
(4, 5) : Or even tuples
>>>

Finally, we can extract various structures from a dictionary in the form of lists.

Exercises

Given the code:

d = {
    "fruits": ["apples", "oranges", "pears", "mangoes"],
    "vegetables": ["tomatoes", "lettuce", "spinach", "green peppers"],
    "meat": ["chicken", "fish", "beef", "ostrich"],
    "dairy": ["yogurt", "milk", "cheese", "ice-cream"]
}
  1. How many keys does d have?
  2. How many values does d have?
  3. What is the value of d["meat"]?
  4. What is the value of d["dairy"][2]?
  5. How do you access "spinach" using the dictionary d?
  6. How do you add a new fruit?
  7. Consider the set of key:value pairs?
    • "Hitchhiker's Guide to the Galaxy": 1
    • "The Restaurant at the End of the Universe": 2
    • "Life, the Universe, and Everything": 3
    • "So Long, and Thanks for all the Fish!": 4
    • "Mostly Harmless": 5
    1. How do you create this set as a dictionary in python?
    2. How do you find which book in the 'trilogy', i.e. what number, "The Restaurant at the End of the Universe" is?
    3. Write a program that starts by declaring the above dictionary as a literal, and outputs the books in order.
    4. Write a program that starts by declaring the above dictionary as a literal, and then asks the user for a number, and prints out name of the book which has the given number.
    5. Write a program the starts by declaring the above dictionary as a literal, then proceeds to switch the keys and values, so that values become keys, and vice versa. Print out the resulting dictionary
  8. Write a program that reads in names until a blank line is entered, and prints out each unique name and the number of times it was entered.
  9. Write a program the reads strings until a blank line is encountered. For each string entered, treat the portion of the string up to the first colon (or the entire string if no colon is present) as a key name, and everything after the first colon as a value. If the key portion has been entered before, print out the old value paired with that key, and then change the value to the newly entered one. After the blank line, print out a neat list of key value pairs.
  10. A small arts and crafts store owner in the middle of the Karoo has recently upgraded to a computerised point of sale system, and wants to do the same for his guest book. Customers have previously left their names a small paragraph of comment in the book. The owner would like his customers to be able to walk up to a computer near the exit, type in their names, and enter a brief comment. He's only interested in a customer's most recent comments, and doesn't want store old comments. So repeat customer's must be able to update their previous comments. When a repeat customer types in their name, their previous comment is displayed back to them, and they are afforded the opportunity to enter a new comment. Should they enter a blank line instead of a comment, their previous comment is preserved. Also, if instead of a customer name the special command 'quit' is entered, the program exits. Similarly the command 'showcomments' causes all customers' names to be displayed, followed by their comments slightly indented. Customer's must be able to enter their names in a case insensitive manner.
  11. Extend your solution to the previous problem, by allowing customers to enter multi-line comments, and to terminate their comments by entering a blank line. If the comment is entirely blank, i.e. the first line is blank, then it does not overwrite the former comment if any. Also, ensure that when the comments are outputted back, either because of the 'showcomments' command, or a repeat customer entering their name, that the line width of the outputted comments does not exceed 60 characters, nor break a word in two, i.e. lines are only broken on white space.
  12. What happens if you make an element of a dictionary point to itself.
[Prev: Tuples] [Course Outline] [Next: Strings in Depth]