Overview

Dictionaries in programming are an extremely powerful tool when you want to associate two types of information together efficiently. For example, being able to look up a person’s phone number from their name. Today is focused on the syntax and basic use of them, but you will learn lots more about them in future computer science classes!

Basic Learning Objectives

Before class, you should be able to:

  • Make a new dictionary
  • Add key-value pairs to a dictionary
  • Look up the value associated with a key

Advanced Learning Objectives

After class, you should be able to:

  • Use a dictionary to solve a programming problem
  • Use the accumulator pattern with a dictionary

Resources

You should readthe following (it’s a slightly older version of the textbook that we’ve been using):

Checks

Submit answers to the following on Moodle:

  1. What will the following code print?
     d = {'spring': 'autumn', 'autumn': 'fall', 'fall': 'spring'}
     print d['autumn']
    
  2. In order to get the last line to print “success”, what should the value x (in the last line) be?
     d = { 'work': 'success', 'success': 'failure', 'failure': 'money', 'time': 'work', 'industry': 'time'}
     print d[d[x]]
    
  3. What does the following block of code do?
     d =  {'a': 2, 'b': 3, 'c': 1}
     e = {}
     for c in d:
         e[d[c]] = c
     print(e)