Activity 2-5

October 20, 2015

Task 1: Practice Evaluating Python Dictionaries

Download and save ACT2-5.py. Open it in IDLE and press F5. Three variables are already defined: origString, freqDict, and phoneDict.

The Dictionaries

  1. Look at freqDict.
    • What type are the keys?
    • What type are the values?
  2. Look at phoneDict.
    • What type are the keys?
    • What type are the values?

Evaluating Individual Keys

  1. The syntax for evaluating the key 'a' in the freqDict dictionary is freqDict['a']. Try this in a Python shell.
  2. Evaluate the keys 'hat' and 'the' in the freqDict dictionary.
  3. Evaluate the keys 'Carol' and 'Doug' in the phoneDict dictionary.

Test if a Key is in a Dictionary

  1. Use the key in dict syntax to determine if the string 'mat' is a key in freqDict.
  2. Use the in syntax to determine if the string 'Alice' is in phoneDict.

Get Lists of Keys and Values

  1. Use the keys() function to get a list of keys for freqDict and then for phoneDict.
  2. Use the values() function to get a list of keys for freqDict and then for phoneDict.
  3. Suppose we want to print both the keys and values in a dictionary. Which of the two functions (keys() or values()) would make this task easier? Why? How would you accomplish this task with the other function (you don't have to write code, just think about it)?

Task 2: Manipulating Dictionaries

Adding, Removing, and Updating Key-Value Pairs

  1. Add the key 'mat' with the value 0 to freqDict. Verify your change by evaluating freqDict.
  2. Remove the key 'cat' from freqDict. Verify your change by evaluating freqDict.
  3. Put the key 'Alice' with the value '401-555-5555' in phoneDict. What happened to the dictionary? What does this mean about keys?

Dictionaries vs. Lists

  1. Inspect the printDict() function. How does it print the key-value pairs for a dictionary? Run printDict() on freqDict and then phoneDict.
  2. Now inspect the printList() function. Since this function takes a list, use the split() function to split origString on whitespace. Pass this list to the printList() function. What differences and similarities do you notice when you compare the output of printDict() and printList()?

Task 3: Computing a Dictionary of Word Frequencies

  1. Take a look at the wordFreq() function. Fill in the function so that it actually returns a dictionary of word frequencies instead of always an empty dictionary.