CMU 15-110: Principles of Computing
Maps (Dictionaries)


  1. Motivating Example: getState(city)
  2. Creating Dictionaries
  3. Dictionary Properties
  4. Dictionary Operations
  5. Example: isAnagram with a Dictionary

  1. Motivating Example: getState(city)
    stateMap = { 'Pittsburgh':'PA', 'Chicago':'IL', 'Seattle':'WA', 'Boston':'MA' } def getState(city): if (city in stateMap): return stateMap[city] else: return None print(getState('Chicago')) print(getState('Toronto'))

  2. Creating Dictionaries
    • Create an empty dictionary
      d = dict() print(d)

    • Create a dictionary with some values in it
      d = { 'cow':5, 'dog':98, 'cat':1 } print(d['cow']) print(d)

  3. Dictionary Properties
    1. Dictionaries (aka 'maps') map keys to values: d[key] = value
    2. Keys are restricted: must be unique and must be immutable
    3. Values are unrestricted: may repeat and may be mutable
    4. Dictionaries are very efficient

  4. Dictionary Operations
    Operation Result
    len(d) the number of keys in d
    for key in d loop over each key in d
    key in d test if d has the given key
    key not in d test if d does not have the given key
    d[key] get the value that is associated with the given key. Raises a KeyError if key is not in d.
    d[key] = value set d[key] to value (replace old value if there was one)

  5. Example: isAnagram with a Dictionary
    Compare this solution to our earlier version here:
    def letterCounts(s): # improved version now returns a dictionary instead of a list, # and now uses the character as the key, instead of (ord(c) - ord('A') counts = dict() for c in s.upper(): if ((c >= 'A') and (c <= 'Z')): if (c in counts): counts[c] += 1 else: counts[c] = 1 return counts def isAnagram(s1, s2): return (letterCounts(s1) == letterCounts(s2)) def testIsAnagram(): print('Testing isAnagram()...', end='') assert(isAnagram('', '') == True) assert(isAnagram('abCdabCd', 'abcdabcd') == True) assert(isAnagram('abcdaBcD', 'AAbbcddc') == True) assert(isAnagram('abcdaabcd', 'aabbcddcb') == False) print('Passed!') testIsAnagram()