Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals of Programming I Dictionaries

Similar presentations


Presentation on theme: "Fundamentals of Programming I Dictionaries"— Presentation transcript:

1 Fundamentals of Programming I Dictionaries
Computer Science 111 Fundamentals of Programming I Dictionaries

2 Data Structures A data structure is a means of organizing several data elements so they can be treated as one thing A sequence is a data structure in which the elements are accessible by position (first .. last) A dictionary is a data structure in which the elements are accessible by content

3 Examples of Dictionaries
Dictionary Phone book Thesaurus Encyclopedia Cookbook World Wide Web Elements may also be ordered alphabetically, but they need not be

4 Examples of Dictionaries
Dictionary Phone book Thesaurus Encyclopedia Cookbook World Wide Web An element is accessed by content This content can be A word A person’s name A food type A text phrase or an image

5 Examples of Dictionaries
Dictionary Phone book Thesaurus Encyclopedia Cookbook World Wide Web An element is accessed by content This content can be A word A person’s name A food type A text phrase or an image Each content is called a key Each associated element is called a value

6 Characteristics of a Dictionary
A dictionary is a set of keys associated with values The keys are unique and need not be ordered by position or alphabetically Values can be duplicated Keys and values can be of any data types

7 Examples of Keys and Values
Some hexadecimal (base16) digits and their values A database of Ken’s info 'A' 10 'B' 11 'C' 12 'D' 13 'E' 14 'F' 15 'name' 'Ken' 'age' 68 'gender' 'M' 'occupation' 'teacher' 'hobbies' ['movies', 'gardening']

8 Dictionaries in Python
hexdigits = {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} an_empty_one = {} Syntax: {<key> : <value>, … , <key> : <value>}

9 Acessing a Value with a Key
>>> database = {'name':'Ken', 'age':67, 'gender':'M', 'occupation':'teacher'} >>> database['name'] 'Ken' >>> database['age'] 67 The subscript expects a key in the dictionary and returns the associated value <dictionary>[<key>]

10 Key Must be in the Dictionary
>>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> database['hair color'] Traceback (most recent call last): File "<pyshell#6>", line 1, in -toplevel- database['hair color'] KeyError: 'hair color'

11 Guard Access with an if >>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> if 'hair color' in database: database['hair color'] The in operator can be used to search any sequence or dictionary

12 Alternative: Use the get Method
>>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> database.get('hair color', None) None If the key (first argument) is in the dictionary, the value is returned Otherwise, the default value (second argument) is returned

13 The for Loop Visits All Keys
>>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> for key in database: print(key, database[key]) gender M age 68 name Ken occupation teacher

14 Inserting a New Key/Value
>>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> database['hair color'] = 'gray' If the key is not already in the dictionary, Python creates one and inserts it with the associated value

15 Inserting a New Key/Value
hexdigits = {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} >>> for i in range(10): hexdigits[str(i)] = i >>> hexdigits {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, '1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8} Insert the remaining hexadecimal digits and their integer values

16 Replacing an Existing Value
>>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> database['age'] = database['age'] + 1 If the key is already in the dictionary, Python replaces the associated value with the new one

17 Removing a key >>> database = {'name':'Ken', 'age':68, 'gender':'M', 'occupation':'teacher'} >>> database.pop('age', None) 68 The pop method removes the key and its associated value and returns this value

18 Another Application: Non-Directive Psychotherapy
Good morning, Ken, how can I help you today? > The therapist opens the session with a leading question, and waits for the patient’s reply

19 Another Application: Non-Directive Psychotherapy
Good morning, Ken, how can I help you today? > My teacher hates me. The therapist lets the patient provide most of the content The patient replies with a statement

20 Another Application: Non-Directive Psychotherapy
Good morning, Ken, how can I help you today? > My teacher hates me. Why do you say that your teacher hates you? The therapist lets the patient provide most of the content She responds by rephrasing the patient’s statement as a request for more information She includes the patient’s content by switching persons in the replies (‘me’ becomes ‘you,’ ‘my’ becomes ‘your’, etc.)

21 Another Application: Non-Directive Psychotherapy
Good morning, Ken, how can I help you today? > My teacher hates me. Why do you say that your teacher hates you? > She always calls on the girls in the class. The therapist lets the patient provide most of the content She responds by rephrasing the patient’s statement as a request for more information She includes the patient’s content by switching persons in the replies (‘I’ becomes ‘you,’ ‘my’ becomes ‘your’, etc.)

22 Another Application: Non-Directive Psychotherapy
Good morning, Ken, how can I help you today? > My teacher hates me. Why do you say that your teacher hates you? > She always calls on the girls in the class. Please tell me more. > Alternatively, the therapist tries to move the conversation forward with a hedge.

23 The Doctor Program The patient inputs a sentence
The doctor replies by either Exploding the patient’s sentence into a list of words Changing the person of each pronoun in the list Converting the list back to a string Prepending a qualifier to the string to create a question Printing the result or Printing a randomly chosen hedge Steps 1 and 2 are repeated until the patient enters ‘quit’

24 Data Structures for the Program
A list of qualifiers to be chosen at random A list of hedges to be chosen at random A dictionary of pronouns and their replacements

25 Data Structures for the Program
qualifiers = ['Why do you say that ', 'You seem to think that ', 'Did I just hear you say that '] replacements = {'I': 'you', 'me': 'you', 'my': 'your', 'we': 'you', 'us': 'you'} The function random.choice returns a randomly selected item from a given sequence import random print(random.choice(qualifiers))

26 The Main Loop The function main handles the interaction with the user
def main(): """Handles user interaction with the program.""" print('Good morning, how can I help you today?') while True: sentence = input('> ') if sentence.upper() == 'QUIT': break print(reply(sentence)) print('Have a nice day!') The function main handles the interaction with the user The function reply transforms the patient’s input into the doctor’s reply and returns it

27 Defining reply def reply(sentence): """Returns a reply to the sentence.""" return random.choice(qualifiers) + changePerson(sentence) reply prepends a randomly chosen qualifier to the result of changing persons in the patient’s input sentence The result returned is in the form of a question that includes most of the content of the patient’s input sentence

28 The Strategy for changePerson
Explode the sentence into a list of words Loop through the list and build a new list as we go If the word in the input list is in the replacements dictionary, add its replacement to the new list Otherwise, just add the original word to the new list When the loop is finished, congeal the new list to a string of words and return it

29 Defining changePerson
def changePerson(sentence): """Returns the sentence with pronouns changed.""" oldlist = sentence.split() newlist = [] for word in oldlist: if word in replacements: newlist.append(replacements[word]) else: newlist.append(word) return " ".join(newlist) Instead of the if-else statement, we could accomplish the replacement more simply using get: newlist.append(replacements.get(word, word))

30 Defining changePerson
def changePerson(sentence): """Returns the sentence with pronouns changed.""" oldlist = sentence.split() newlist = [] for word in oldlist: newlist.append(replacements.get(word, word)) return " ".join(newlist) Instead of using an if-else statement, we could accomplish the replacement more simply by using get

31 Improvements Add hedges
Keep track of earlier patient inputs, so the doctor can refer back to them Spot keywords in a patient’s reply, and respond with associated sentences

32 For Wednesday Start Chapter 6


Download ppt "Fundamentals of Programming I Dictionaries"

Similar presentations


Ads by Google