Homework Solution

Dictionaries

Problems to be Submitted (20 points)

  1. (5 points)

    items = []
    for k in data:
        items.append( (k, data[k]) )
    
    or if you wish to use list comprehension syntax
    items = [ (k,data[k]) for k in data ]
    

  2. (5 points)

    Here is one possible approach...

    if 'CA' in captial:
        val = capital['CA']
    else:
        capital['CA'] = 'Springfield'
        val in 'Springfield'
    
    Here is another way to express the logic...
    if 'CA' not in capital:
        captial['CA'] = 'Springfield'
    val = capital['CA']
    

  3. (10 points)

    Here is a typical approach using a condition to detect newly encountered characters.

    def letterFrequency(word):
        freq = {}
        for c in word:
    	if c not in freq:
    	    freq[c] = 1    # first time
    	else:
    	    freq[c] += 1   # one additional time
        return freq
    

    Here is a more preferable approach that better leverages the get method of the dictionary to retrieve a previous count, yet with 0 as the result for something not found.

    def letterFrequency(word):
        freq = {}
        for c in word:
    	freq[c] = 1 + freq.get(c,0)
        return freq
    

Last modified: Monday, 03 December 2018