CMU 15-110: Principles of Computing
Maps (Dictionaries)
- Motivating Example: getState(city)
- Creating Dictionaries
- Dictionary Properties
- Dictionary Operations
- Example: isAnagram with a Dictionary
- 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'))
- 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)
- Create an empty dictionary
- Dictionary Properties
- Dictionaries (aka 'maps') map keys to values:
d[key] = value
- Keys are restricted: must be unique and must be immutable
- Values are unrestricted: may repeat and may be mutable
- Dictionaries are very efficient
- Dictionaries (aka 'maps') map keys to values:
- 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) - 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()