Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.

Similar presentations


Presentation on theme: "COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information."— Presentation transcript:

1 COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information

2 Recap: Dictionaries  A dictionary organizes information by association, not position  It is written as a sequence of key/value pairs separated by commas  Pairs are sometimes called entries  Enclosed in curly braces ({ and })  A colon (:) separates a key and its value  { key1:value1, key2:value2, … }  Keys must be immutable values such as strings, numbers and tuples  Values can be of any Python data type  Unordered collection of references contacts = {'bill': '353-1234', 'rich': '269-1234', 'jane': '352-1234'} contacts = {'bill': '353-1234', 'rich': '269-1234', 'jane': '352-1234'} COMPSCI1012

3 Recap: Dictionaries  Dictionaries  Items can be retrieved from the dictionary  Add a new key/value pair to a dictionary using [ ]  Use [ ] also to replace a value at an existing key CompSci 1013 english_italian = {"yes":"si","bye":"ciao","maybe":"forse","thank you":"grazie"} print(english_italian["bye"] ) english_italian["never"] = "mai" english_italian = {"yes":"si","bye":"ciao","maybe":"forse","thank you":"grazie"} print(english_italian["bye"] ) english_italian["never"] = "mai" DEMO Example01.py ciao Add a new pair

4 Recap: Operators  Common Operators:  len(my_dict) – number of key:value pairs in the dictionary  element in my_dict – boolean, is element a key in the dictionary?  for key in my_dict – iterates through the keys of a dictionary  Examples: COMPSCI1014 print(len(english_italian)) print("yes" in english_italian) for word in english_italian: print(english_italian[word]) print(len(english_italian)) print("yes" in english_italian) for word in english_italian: print(english_italian[word]) 5 True mai si ciao grazie forse test for existence: Check if “yes” exists in the dictionary

5 Learning outcomes  At the end of this lecture, students should be able to:  Delete key:value pairs from a dictionary  Create a list of keys, values, key:value tuples from a dictionary  Use dictionary objects to manage a small file of information  Case study 1: Printing the frequency of each word in the text.  Case study 2: Phonebook Lookup Application  References:  Dictionaries  https://docs.python.org/3.3/tutorial/datastructures.html#dictionaries CompSci 1015

6 Deleting a key:value pair  The del operator is used to delete a key:value pair from the dictionary.  Note: del lets you delete individual items from a dictionary by key. CompSci 1016 my_dict = {"a": 4, "b": 6, "c": 5} print("1.", my_dict) del my_dict["b"] print("2.", my_dict) del my_dict["a"] print("3.", my_dict) my_dict = {"a": 4, "b": 6, "c": 5} print("1.", my_dict) del my_dict["b"] print("2.", my_dict) del my_dict["a"] print("3.", my_dict) 1. {'a': 4, 'b': 6, 'c': 5} 2. {'a': 4, 'c': 5} 3. {'c': 5} Delete the "b": 6 pair Delete the "a": 4 pair

7 Deleting a key:value pair  The del operator gives an error if the key of the key:value pair being deleted is not in the dictionary.  Because of this, it is customary to test before deleting a key:value pair. CompSci 1017 my_dict = {"a": 4, "b": 6, "c": 5} print("1.", my_dict) if "b" in my_dict: #Test first del my_dict["b"] print("2.", my_dict) del my_dict["z"] print("2.", my_dict) my_dict = {"a": 4, "b": 6, "c": 5} print("1.", my_dict) if "b" in my_dict: #Test first del my_dict["b"] print("2.", my_dict) del my_dict["z"] print("2.", my_dict) 1. {'b': 6, 'c': 5, 'a': 4}…. 2. {'c': 5, 'a': 4} … KeyError: 'z' DEMO Example02.py

8 Dictionary Methods  The keys, the values, the associations as tuples, can be obtained from a dictionary object using the methods:  my_dict.items() – to access all the key/value pairs as tuples  my_dict.keys() – to access all the keys  my_dict.values() – to access all the values  Note:  Dictionaries have no concept of order among elements. They are simply unordered.  Dictionary Keys Are Case-Sensitive CompSci 1018

9 Dictionary Methods  The elements in these collections can be accessed using a for … in loop. CompSci 1019 my_dict = {"a": 4, "b": 6, "c": 5} for letter in my_dict.keys(): print(letter) for number in my_dict.values(): print(number) for item in my_dict.items(): print(item) my_dict = {"a": 4, "b": 6, "c": 5} for letter in my_dict.keys(): print(letter) for number in my_dict.values(): print(number) for item in my_dict.items(): print(item) bcabca DEMO Example03.py 654654 ('b', 6) ('c', 5) ('a', 4) Returns key:value pairs in the dictionary as tuples

10 Dictionary Methods  When a for … in loop is used with a dictionary object, Python loops through each key in the dictionary:  The method items() returns a list of my_dict's (key, value) tuple pairs CompSci 10110 my_dict = {"a": 4, "b": 6, "c": 5} for letter in my_dict.keys(): print(letter) for key in my_dict: print(key) my_dict = {"a": 4, "b": 6, "c": 5} for letter in my_dict.keys(): print(letter) for key in my_dict: print(key) Note that both these loops do the same job bcabca bcabca for k,v in my_dict.items(): print(k,v) for item in my_dict.items(): print(item) for k,v in my_dict.items(): print(k,v) for item in my_dict.items(): print(item) c 5 b 6 a 4 ('b', 6) ('c', 5) ('a', 4)

11 Exercise 1  What is the output after executing the following code? CompSci 10111 days = {'Mo':'Monday', 'Tu':'Tuesday', 'We':'Wednesday'} for key in days: print(key, end=" ") print() for value in days.values(): print(value, end=" ") print() days = {'Mo':'Monday', 'Tu':'Tuesday', 'We':'Wednesday'} for key in days: print(key, end=" ") print() for value in days.values(): print(value, end=" ") print()

12 Converting into a List of …  Often it is useful to convert the individual keys (or values, or item tuples) of the dictionary into lists by enclosing the keys (or values, or item tuples) in the method list(): CompSci 10112 my_dict = {"a": 4, "b": 6, "c": 5} items_list = list(my_dict.items()) keys_list = list(my_dict.keys()) values_list = list(my_dict.values()) print("items list", items_list) print("keys list", keys_list) print("values list", values_list) my_dict = {"a": 4, "b": 6, "c": 5} items_list = list(my_dict.items()) keys_list = list(my_dict.keys()) values_list = list(my_dict.values()) print("items list", items_list) print("keys list", keys_list) print("values list", values_list) items list [('a', 4), ('c', 5), ('b', 6)] keys list ['a', 'c', 'b'] values list [4, 5, 6] DEMO Example03.py

13 Case Study 1 Printing Frequency Table  Task:  Complete the word_count() function which takes a piece of text as input and prints the frequency of each word in the text. You may assume that the text has no punctuation and words are separated by blank spaces.  Arguments: text (a string)  Prints: the frequency table  Example: >>> word_count('all animals are equal but some animals are more equal than others') Unordered collection COMPSCI10113 others appears 1 time. than appears 1 time. some appears 1 time. equal appears 2 times. but appears 1 time. are appears 2 times. animals appears 2 times. all appears 1 time. more appears 1 time. DEMO Example04.py

14 Case Study 1 Printing Frequency Table  Steps: Splitting the text into a list of wordsCreate a dictionary Create an entry for each distinct item word_count('all animals are equal but some animals are more equal than others') keyall value1 keyanimals value2 keyare value2 keyequal value2 keybut value1 … How? Examples: COMPSCI10114

15 Case Study 1 Creating Entries  Iterate through all items in the word list If we encounter the item for the first time, Create a new entry Else Increment value by 1 at the corresponding entry word_count('all animals are equal but some animals... key value key value key value key value key value … all 1 animals 1 are 1 equals 1 but 1 COMPSCI10115 key value some 1 2

16 Case Study 1 Printing Frequency Table  Steps:  How to check for existence?  How do we increment the value of the corresponding entry?  How do we create a new entry? if word in counters: counters[word] = counters[word] + 1 counters[word] = 1 COMPSCI10116

17 Case Study 2 Phonebook Lookup Application  Task:  Complete the lookup() function which takes a phonebook dictionary as input. In the dictionary, the names of individuals (the keys) are mapped to strings containing phone numbers (the values). Your function should provide a simple user interface through which a user can enter the name of an individual and obtain the phone number assigned.  Arguments: phonebook dictionary  Prints: phone number of an individual  Example: >>>lookup({"Angela":"3737599-86620", "Ann":"3737599- 84947", "Adriana":"3737599-87113","Jing":"3737599- 82286"}) The dictionary phonebook COMPSCI10117 DEMO Example05.py

18 Case Study 2 Phonebook Lookup Application  Input – Process – Output  Input: the phonebook dictionary  Process – lookup  Output – return the phone number COMPSCI10118 Enter name: Angela 3737599-86620 Do you want to continue(y/n)? y Enter name: Ann 3737599-84947 Do you want to continue(y/n)? y Enter name: abc The name you entered is not known. Do you want to continue(y/n)? n

19 Case Study 2 Input: Dictionary  The phonebook dictionary:  Existence check:  element in my_dict – returns a boolean. Is element a key in the dictionary?  If the result is yes, prints the value (phone number) of the corresponding entry keyAngela value3737599-86620 keyAnn value3737599-84947 keyAdriana value3737599-87113 keyJing value3737599-82286 COMPSCI10119

20 Case Study 2 Algorithm Enter a name Continue? y/n y Does the dictionary contain the name? True Print the phone number Print an error message COMPSCI10120 n

21 Case Study 2 Algorithm Create a while loop Enter a name If the dictionary contains the name(key) Print the corresponding phone number (value) Else Print an error message COMPSCI10121

22 Exercise 2: Printing Frequency Table  Task:  Complete the word_count2() function which asks the user to enter a message and prints the frequency of each word in the message.  Prints: the frequency table  Example: >>> word_count2() Enter a message: all animals are equal but some animals are more equal than others >>> word_count2() Enter a message: all animals are equal but some animals are more equal than others others appears 1 time. than appears 1 time. some appears 1 time. equal appears 2 times. but appears 1 time. are appears 2 times. animals appears 2 times. all appears 1 time. more appears 1 time. others appears 1 time. than appears 1 time. some appears 1 time. equal appears 2 times. but appears 1 time. are appears 2 times. animals appears 2 times. all appears 1 time. more appears 1 time. COMPSCI10122

23 Summary  The del operator is used to delete a key:value pair from the dictionary.  The keys, the values, the associations as tuples can be obtained from a dictionary object using the methods:  my_dict.items() – to access all the key/value pairs as tuples  my_dict.keys() – to access all the keys  my_dict.values() – to access all the values  Often it is useful to convert the individual keys (or values, or item tuples) of the dictionary into lists by enclosing the keys (or values, or item tuples) in list() CompSci 10123


Download ppt "COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information."

Similar presentations


Ads by Google