# Intro to Python ## Week 10 ### Dictionaries and exceptions --- ## Agenda - Tues: Dictionaries (Ch 12) - Thurs: Exceptions (Ch 13) notes: - [ ] dict for classify_text "mapping" - [ ] poor-mans machine learning using dict lookup - [ ] `.get()` - [ ] global dict with game data - [ ] `dict`s as kwargs instead of mutable args - [ ] insidious semantic/logic `dict` errors (mutable default args to functions) - [ ] `__dict__` --- ## Auto-lint with ruff Make Sublime Text fix your Python every time you save: [Configure Sublime Text linting](./wk10/configure-sublime-text-linting.html) --- ```python def tokenize(text): return str(text).split() ``` --- ```python def classify_text(text): """ Recognize user intent: yes, no, or unknown >>> classify_text('Y') 'yes' >>> classify_text('NOWAY') 'no' >>> classify_text("I don't know!!") 'unknown' """ words = tokenize(text.lower()) score = 0 for w in words: score += int(w[0] == 'y') score -= 1 * int(w[0] == 'n') score /= len(words) if score > 0.5: return 'yes' elif score < -.1: return 'no' return 'unknown' ``` --- ```python rules = { 'yes': { 'y': 1, 'yea': 1, 'sure': 1, 'ok': 1, }, 'no': { 'n': 1, 'nope': 1, }, 'exit': { 'x': 1, 'q': 1, 'quit': 1, }, } ``` --- ```python def classify_text(text): """ Recognize user intent: yes, no, unknown, left, right >>> classify_text('Y') 'yes' >>> classify_text('NOWAY') 'no' """ tokens = tokenize(text.lower()) category_scores = {} for tok in tokens: for category, rule in rules.items(): for alias, points in rule.items(): if tok == alias: category_scores[category] = category_scores.get(category, 0) + points find_key_of_max_value(category_scores) ``` --- ```python def find_key_of_max_value(d): """ find the maximum value key in a dictionary >>> find_max_value({'yes': 1, 'no': 2, 'unknown': 3}) 'unknown' """ max_value = 0 for k, v in d.items(): if v > max_value: max_value = v key_of_max_value = k return key_of_max_value ``` --- ```python def find_max_value(d): """ find the maximum value key in a dictionary >>> find_max_value({'yes': 1, 'no': 2, 'unknown': 3}) 'unknown' """ value_key_pairs = [(v, k) for (k, v) in d.items()] # return sorted(value_key_pairs)[-1][1] return max(value_key_pairs)[1] ``` ---