1 / 24

CS 177 Week 11 Recitation Slides

CS 177 Week 11 Recitation Slides. Dictionaries, Tuples. 1. Announcements. 2. Why Do We Use Dictionary 1/3. Suppose we have the following table, that associates an identifier to a student name: This association is a relationship between the identifier and the student name. 3.

milton
Download Presentation

CS 177 Week 11 Recitation Slides

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 177 Week 11 Recitation Slides Dictionaries, Tuples 1

  2. Announcements 2

  3. Why Do We Use Dictionary 1/3 • Suppose we have the following table, that associates an identifier to a student name: • This association is a relationship between the identifier and the student name 3

  4. Why Do We Use Dictionary 2/3 • Can we represent this relationship using lists? • Yes, we can. Look at the following: • myList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] • However, we have to access the elements of the list above by using integer indexes: • >>> myList[0] • ['S1', 'Kate'] • >>> myList[0][1] • 'Kate‘ • >>> myList[0][0] • 'S1' CS177 - Spring 2011

  5. Why Do We Use Dictionary 3/3 But we can not “ask” our Python list: please give me back the name of the student associated to the identifier ‘S1’ If we need to do that, we have to use a new Python construct: the dictionary CS177 - Spring 2011

  6. Using Dictionaries in Python • Python dictionaries store data element as a pairs of key/value data in the form of key:value • “associative lists” surrounded by { }, rather than [ ] in lists • KEYVALUE 6

  7. Creating Dictionaries • We can store the data in the above table by using python dictionary as follows • >>> StuDict = {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’} • We can also do the following, • >>> StuDict = {} • >>> StuDict[‘S1’] = ‘Kate’ • >>> StuDict[‘S2’] = ‘Brittany’ • >>> StuDict[‘S3’] = ‘Alice’ 7

  8. Creating Dictionaries • We can also create a dictionary from a list • >>> myList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] • >>> StuDict = dict(myList) • >>> mydict • {'S3': 'Alice', 'S2': 'Brittany', 'S1': 'Kate'} 8

  9. KEY in Dictionary vs. INDEX in List • Type • Key (dictionary): Any immutable type, usually strings or integers • Index (list):Integers • An example of a string used as a dictionary key >>> StuDict = {'S1':'Kate', 'S2':'Brittany', 'S3':'Alice'} >>>print (StuDict['S1']) ‘Kate’ • An example of an integer used as a dictionary key >>> StuDict = {1:'Kate', 2:'Brittany', 3:'Alice'} >>>print (StuDict[1]) ‘Kate’ 9

  10. KEY in Dictionary vs. INDEX in List • Definition • Key (dictionary): specified by users, not based on ordering • Index (list): provided by system, implicitly based on list ordering • Example • Dictionary works without ordering >>> StuDict = {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’} >>>print StuDict[‘S3’] ‘Kate’ >>> StuDict = {‘S3’:‘Kate’, ‘S2’:‘Brittany’, ‘S1’:‘Alice’} >>>print StuDict[‘S3’] ‘Kate’ • List works with implicit ordering: >>>StudList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] • We cannot change element’s index in a list 10

  11. Dictionary Operations • >>> inventory = {'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312} • Getting an element from the dictionary • >>> inventory['oranges'] • 525 • Remove the entry from the dictionary • >>> del inventory['pears'] • >>> print(inventory) • {'apples': 430, 'oranges': 525, 'bananas': 312} 11

  12. Dictionary Operations • The len function also works on dictionaries; it returns the number of key-value pairs: • >>> len(inventory) • 3 12

  13. Dictionary Methods • Getting all keys of a dictionary • >>> list(inventory.keys()) • ['oranges', 'apples', 'pears', 'bananas'] • Getting all values from a dictionary • >>> list(inventory.values()) • [525, 430, 217, 312] 13

  14. Dictionaries and for loops • >>> for key in inventory: • print("Value : ", inventory[key]) • Value : 525 • Value : 430 • Value : 217 • Value : 312 14

  15. Dictionary Example • def readFile(): • file = open("names.txt", "r") • contents = file.read() • file.close() • lines = contents.split("\n") • phonebook = {} • for line in lines: • items = line.split(":") • phonebook[items[0]] = items[1] • return phonebook 15

  16. Dictionary Example • def findPhoneNumber(name): • phonebook = readFile() • for key in phonebook: • if(key.lower().find(name.lower()) != -1): • print("Phone number for ", key, " is", phonebook[key]) • >>> findPhoneNumber('parsoN') • Phone number for Andrew Parson is 8806336 • >>> 16

  17. Populating Dictionaries We can populate dictionaries with list >>>dict([(x, chr(x+97)) for x in range(10)]) {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'}

  18. Tuples • A tuple consists of a number of values separated by commas, surrounded by () • (x, y) coordinate pairs • Student records in the database

  19. Constructing Tuples We construct a tuple corresponding to each row of the following table: >>>Tup1 = (‘S1’, ‘Kate’) >>>Tup2 = (‘S2’, ‘Brittany’) >>>Tup3 = (‘S3’, ‘Alice’) We can also build a tuple of tuples… >>>StuTup = (Tup1, Tup2, Tup3) >>>print (StuTup) ((‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’))

  20. Constructing Tuples Getting an element of a Tuple in the same way we get an element of a list: >>> StuTup[1] ('S2', 'Brittany') >>> StuTup[1][0] 'S2' >>> StuTup[1][1] 'Brittany' Tuples are immutable >>>StuTup[0] = ((‘S5’, ‘Jane’)) error message -- no assignment

  21. Tuple Assignment • A tuple of variables on the left can be assigned values from a tuple on the right: >>> a = 10 >>> b = 20 >>> (a, b) = (b, a) >>> a 20 >>> b 10 • Number of variables on the left and the number of values on the right must be the same! >>> (a, b, c, d) = (1, 2, 3) ValueError: need more than 3 values to unpack

  22. Tuples as Return Values def function(a, b): sum = a + b product = a * b return(sum, product) >>> (a, b) = function(10, 20) >>> a 30 >>> b 200 >>> result = function(50, 100) >>> result[1] 5000 >>> result[0] 150

  23. Now Creating a Dictionary from a List of Tuples Given a list of tuples as follows [(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)] Let’s create a dictionary with the dict function dict([(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)]) A tuple in the list is a pair of key:value data in the dictionary >>> dict([(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)]) {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’}

  24. QUESTIONS? 24

More Related