Homework Assignment

Dictionaries


Overview

Topic: Dictionaries
Related Reading: Chapter 23
Due:

Please make sure you adhere to the policies on academic integrity.


Problems to be Submitted (20 points)

  1. (5 points)

    Assume that the method dict.items() did not exist. Give a small code fragment that produces a list of (key,value) pairs for a dictionary named data.

  2. (5 points)

    Although not discussed in the chapter, Python dictonaries also support a method named setdefault, documented as follows:

    	setdefault(key, default)
    	  if key is in the dicitonary, return its value. If
    	  not, insert key with a value of default and
    	  return default.
    Demonstrate your understanding by giving a snippet of code with logic that is equivalent to the following:
    val = capital.setdefault('CA','Springfield')
    
    presuming that capital is an existing dictionary. You are not allowed to use the setdefault method in your answer.

  3. (10 points)

    Write a function with signature letterFrequency(word) that returns a dictionary that maps each occurrying letter of the string word to a count of the number of times that letter occurs. For example, letterFrequency('Mississippi') should return a dictionary with entries {'M':1, 'i':4, 's':4, 'p':2}

    With proper use of dictionaries, your function should require only a single loop through the characters of the string, updating the frequency counts as you proceed. You should avoid use of the str.count method (which itself would depend on a loop).


Last modified: Friday, 07 December 2018