Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.

Slides:



Advertisements
Similar presentations
Dictionaries: Keeping track of pairs
Advertisements

Guide to Programming with Python
Python Mini-Course University of Oklahoma Department of Psychology Lesson 16 Dictionaries 5/10/09 Python Mini-Course: Lesson 16 1.
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.
INLS 560 – D ICTIONARIES Instructor: Jason Carter.
Sequences The range function returns a sequence
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
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.
Built-in Data Structures in Python An Introduction.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
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.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
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.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Copyright © 2013 by John Wiley & Sons. All rights reserved. SETS AND DICTIONARIES CHAPTER Slides by James Tam Department of Computer Science, University.
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.
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
COMPSCI 107 Computer Science Fundamentals
COMPSCI 107 Computer Science Fundamentals
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
CSc 110, Spring 2017 Lecture 29: Sets and Dictionaries
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
CSc 120 Introduction to Computer Programing II
CSc 110, Autumn 2016 Lecture 27: Sets and Dictionaries
Department of Computer Science,
Data types: Complex types (Dictionaries)
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
COSC 1323 – Computer Science Concepts I
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Intro to Computer Science CS1510 Dr. Sarah Diesburg
ARRAYS 1 GCSE COMPUTER SCIENCE.
Recitation Outline C++ STL associative containers Examples
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
15-110: Principles of Computing
Python Review
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Introduction to Dictionaries
Dictionary.
Tuple.
Presentation transcript:

Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming

 At the end of this lecture, students should be able to:  understand what a dictionary is  create a dictionary object  add items to a dictionary  retrieve items from the dictionary  traverse the pairs in a dictionary Learning outcomes CompSci Principles of Programming2

Recap  In CompSci 101 we use three types of sequences: strings, lists and tuples. sequence1 = (5, 7, 2, 6, 4, 3, 9) sequence2 = [5, 7, 2, 6, 4, 3, 9] sequence3 = "This is a sequence of characters" for element in sequence3: print(element * 2) min_value = min(sequence1) max_value = max(sequence2) total = sum(sequence1) element_from_end1 = sequence1[-2] element_from_end3 = sequence3[-2] element_from_end1 = sequence1.index(4) position3 = sequence3.index("uen") part1 = sequence1[2: 5: 3] part2 = sequence2[2: 7: 2] part3 = sequence3[1: 5: 2] sequence1 = (5, 7, 2, 6, 4, 3, 9) sequence2 = [5, 7, 2, 6, 4, 3, 9] sequence3 = "This is a sequence of characters" for element in sequence3: print(element * 2) min_value = min(sequence1) max_value = max(sequence2) total = sum(sequence1) element_from_end1 = sequence1[-2] element_from_end3 = sequence3[-2] element_from_end1 = sequence1.index(4) position3 = sequence3.index("uen") part1 = sequence1[2: 5: 3] part2 = sequence2[2: 7: 2] part3 = sequence3[1: 5: 2] CompSci Principles of Programming3

Python dictionaries  A dictionary is a mapping from a key to its associated data value.  Each key maps to a value.  The key has to be unique and an immutable object.  A phone book is an example of a mapping: the key is the person's name (plus address) and the associated value is their phone number.  The key and its associated value is called a key-value pair or it can be called an item. You can think of a dictionary as a list of pairs, where the first element of the pair, the key, is used to retrieve the second element, the corresponding value. CompSci Principles of Programming4

Creating an object of type dict  Curly braces are used for dictionaries and {} is a dictionary which contains no key-value pairs, i.e., an empty dictionary:  Another way to create an empty dictionary object is (does exactly the same thing as the code above): def main(): english_italian = {} print(english_italian) print(type(english_italian)) main() def main(): english_italian = {} print(english_italian) print(type(english_italian)) main() {} def main(): english_italian = dict() print(english_italian) print(type(english_italian)) main() def main(): english_italian = dict() print(english_italian) print(type(english_italian)) main() {} CompSci Principles of Programming5

dict is a Python type  Note that the name, dict, is a Python type and should not be used as a variable name. def main(): english_italian = dict() main() def main(): english_italian = dict() main() CompSci Principles of Programming6

Creating a dictionary which contains pairs  The dictionary object can be initialised with key-value pairs:  Each associated pair is separated by ':' and the pairs are separated by commas. Note: the keys have to be unique but the associated values do not. def main(): english_italian = {"yes":"si", "bye":"ciao", "no":"no", "maybe":"forse", "thank you":"grazie"} print(english_italian) contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(contacts) main() def main(): english_italian = {"yes":"si", "bye":"ciao", "no":"no", "maybe":"forse", "thank you":"grazie"} print(english_italian) contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(contacts) main() {'maybe': 'forse', 'bye': 'ciao', 'yes': 'si', 'no': 'no', 'thank you': 'grazie'} {'Yi': 7654, 'Jill': 3456, 'Syed': 6754, 'James': 3456} CompSci Principles of Programming7

Visualising the dictionary def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(contacts) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(contacts) main() {'Jill': 3456, 'Syed': 6754, 'James': 3456, 'Yi': 7654} Note: when the key-value pairs are printed, the order is not predictable. CompSci Principles of Programming8

 The keys of a dictionary must be of a type which is immutable such as: string, int, tuple.  The keys of a dictionary must be unique.  The values can be of any type and they do not need to be unique. The keys of the dictionary must be immutable Remember: lists are mutable. CompSci Principles of Programming9

 A dictionary is not a sequence. A dictionary is a collection of key:value pairs.  There is no predictable order to the key:value pairs in a dictionary (the order may change as new pairs are added). Dictionaries are not sequences BTW: lists, strings and tuples are sequences. Sequence elements can be accessed using the index value. CompSci Principles of Programming10

Adding a pair to the dictionary  Key-value pairs can be added to the dictionary using assignment statements: Note: when the key-value pairs are printed, the order is not predictable. def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} contacts["Mark"] = 7654 contacts["Jerry"] = 7004 print(contacts) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} contacts["Mark"] = 7654 contacts["Jerry"] = 7004 print(contacts) main() {'Jerry': 7004, 'Syed': 6754, 'Yi': 7654, 'Mark': 7654, 'Jill': 3456, 'James': 3456} CompSci Principles of Programming11

Changing the associated value in a dictionary  The associated value of a pair can be changed by assigning a different value to the dictionary key. This replaces the old value. def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} contacts["Jill"] = 7654 contacts["Yi"] = 7004 print(contacts) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} contacts["Jill"] = 7654 contacts["Yi"] = 7004 print(contacts) main() {'Syed': 6754, 'Yi': 7004, 'James': 3456, 'Jill': 7654} CompSci Principles of Programming12

Access the value associated with a key  The value associated with a certain key can be accessed using square brackets (enclosing the key): def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} name1 = "Jill" name2 = "James" print(name1, "is at extension:", contacts[name1] ) if contacts[name1] == contacts[name2] : print(name2, "has the same extension") main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} name1 = "Jill" name2 = "James" print(name1, "is at extension:", contacts[name1] ) if contacts[name1] == contacts[name2] : print(name2, "has the same extension") main() Jill is at extension: 3456 James has the same extension CompSci Principles of Programming13

The number of key-value pairs in a dictionary  The len() function can be used with a dictionary object to find out how many key-value pairs are currently in the dictionary: def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(len(contacts), "in dictionary") contacts["Yi"] = 7654 contacts["Jerry"] = 7004 print(len(contacts), "in dictionary") main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} print(len(contacts), "in dictionary") contacts["Yi"] = 7654 contacts["Jerry"] = 7004 print(len(contacts), "in dictionary") main() 4 in dictionary 5 in dictionary CompSci Principles of Programming14

Check if a key is in the dictionary  The 'in' operator can be used to check if a key is in the dictionary: def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} name = "Jack" if name in contacts: print(name, "is at extension:", contacts[name]) else: contacts[name] = 0 if name in contacts: print(name, "is at extension:", contacts[name]) print(contacts) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} name = "Jack" if name in contacts: print(name, "is at extension:", contacts[name]) else: contacts[name] = 0 if name in contacts: print(name, "is at extension:", contacts[name]) print(contacts) main() Jack is at extension: 0 {'Jill': 3456, 'James': 3456, 'Yi': 7654, 'Syed': 6754, 'Jack': 0} CompSci Principles of Programming15

Traversing the pairs in the dictionaries  Use a for … in loop to traverse (visit) each key in the dictionary: def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} for key in contacts: print(key, "-", contacts[key]) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} for key in contacts: print(key, "-", contacts[key]) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} for name in contacts: print(name, "-", contacts[name]) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} for name in contacts: print(name, "-", contacts[name]) main() Same code Yi Jill Syed James CompSci Principles of Programming16

The in operator with dictionaries  An error is raised when accessing a key which is not in the dictionary. Usually you test before accessing a key-value pair. def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} if "Jill" in contacts: #Test first print("Jill", "-", contacts["Jill"]) print(contacts["Izzy"]) main() def main(): contacts = {"Jill": 3456, "James": 3456, "Yi": 7654, "Syed": 6754} if "Jill" in contacts: #Test first print("Jill", "-", contacts["Jill"]) print(contacts["Izzy"]) main() Jill Traceback (most recent call last): File "LectureCode.py", line 5, in print(contacts["Izzy"]) KeyError: 'Izzy' CompSci Principles of Programming17

Exercise  "Story.txt" is a text file. The following program reads the text from the file, converts it to lower case, and creates a dictionary of all the unique words which start with a vowel ("a", "e", "i","o", "u"). Note: the key is the vowel and each word is added to an associated list (the list grows as the text is processed). def main(): vowel_words_dict = get_dictionary_from_file_words("Story.txt") display_results(vowel_words_dict) def get_dictionary_from_file_words(filename): #complete def display_results(vowel_words): #complete main() def main(): vowel_words_dict = get_dictionary_from_file_words("Story.txt") display_results(vowel_words_dict) def get_dictionary_from_file_words(filename): #complete def display_results(vowel_words): #complete main() o - ['on', 'one', 'old', 'only', 'of', 'opportunity', 'official', 'out'] e - ['elder', 'excited', "elder's"] u - [] i - ['indian', 'in', 'if'] a - ['apollo', 'astronaut', 'a', 'and', 'across', 'asked', 'are', 'asked', ''after', 'asked', 'an'] CompSci Principles of Programming18

Exercise CompSci Principles of Programming19

Exercise def get_dictionary_from_file_words(file_name): CompSci Principles of Programming20

Exercise def display_results(vowel_words_dict): o - ['on', 'one', 'old', 'only', 'of', 'opportunity', 'official', 'out'] e - ['elder', 'excited', "elder's"] u - [] i - ['indian', 'in', 'if'] a - ['apollo', 'astronaut', 'a', 'and', 'across', 'asked', 'are', 'asked', ''after', 'asked', 'an'] CompSci Principles of Programming21

Summary  In Python:  dictionaries are used to store key:value pairs (items)  a dictionary object can be created in two ways  items can be added to a dictionary  items can be retrieved from the dictionary  the pairs in a dictionary can be traversed using for … in CompSci Principles of Programming22

Python features used in this lecture english_italian = {"yes":"si", "bye":"ciao", "no":"no", "maybe":"forse", "thank you":"grazie"} english_italian["never"] = "mai" print(english_italian["bye"] ) for word in english_italian: print(english_italian[word]) print(len(english_italian)) CompSci Principles of Programming23