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

Slides:



Advertisements
Similar presentations
Dictionaries: Keeping track of pairs
Advertisements

Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Fundamentals of Python: From First Programs Through Data Structures
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Python Dictionary.
Lecture 05 – Dictionaries.  Consider the following methods of sorting information in a sequence. What is the output produced by each program? 2COMPSCI.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Genome Sciences 373 Genome Informatics Quiz Section 2 April 7, 2015.
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Encoding of String Characters  Randomness and Random Sampling.
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Container Class set  Container Class tuple  Encoding.
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Chapter 9 Dictionaries and Sets.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
For Loop GCSE Computer Science – Python. For Loop The for loop iterates over the items in a sequence, which can be a string or a list (we will discuss.
Dictionaries Ruth Anderson UW CSE 160 Winter
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
More Python Data Structures  Classes ◦ Should have learned in Simpson’s OOP ◦ If not, read chapters in Downey’s Think Python: Think like a Computer Scientist.
COMPSCI 107 Computer Science Fundamentals
COMPSCI 107 Computer Science Fundamentals
10 - Python Dictionary John R. Woodward.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CSc 120 Introduction to Computer Programing II
Department of Computer Science,
Announcements Project 4 due Wed., Nov 7
Data types: Complex types (Dictionaries)
Introduction to Scripting
Lecture 10 Data Collections
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
COSC 1323 – Computer Science Concepts I
Introduction to Python
Python Primer 2: Functions and Control Flow
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CS190/295 Programming in Python for Life Sciences: Lecture 6
I210 review.
Recitation Outline C++ STL associative containers Examples
Datatypes in Python (Part II)
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
Dictionary.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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

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': ' ', 'rich': ' ', 'jane': ' '} contacts = {'bill': ' ', 'rich': ' ', 'jane': ' '} COMPSCI1012

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

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

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  CompSci 1015

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

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

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

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 ('b', 6) ('c', 5) ('a', 4) Returns key:value pairs in the dictionary as tuples

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 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)

Exercise 1  What is the output after executing the following code? CompSci 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()

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 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

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

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

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

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

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":" ", "Ann":" ", "Adriana":" ","Jing":" "}) The dictionary phonebook COMPSCI10117 DEMO Example05.py

Case Study 2 Phonebook Lookup Application  Input – Process – Output  Input: the phonebook dictionary  Process – lookup  Output – return the phone number COMPSCI10118 Enter name: Angela Do you want to continue(y/n)? y Enter name: Ann 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

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 value keyAnn value keyAdriana value keyJing value COMPSCI10119

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

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

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

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