Top Banner
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples
24

CS 177 Week 11 Recitation Slides

Jan 09, 2016

Download

Documents

Milton Ishizaki

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. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 177 Week 11 Recitation Slides

CS 177 Week 11 Recitation Slides

11

Dictionaries, Tuples

Page 2: CS 177 Week 11 Recitation Slides

Announcements

22

Page 3: CS 177 Week 11 Recitation Slides

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

33

StudentID StudentName

S1 Kate

S2 Brittany

S3 Alice

Page 4: CS 177 Week 11 Recitation Slides

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 404/21/23

Page 5: CS 177 Week 11 Recitation Slides

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 504/21/23

Page 6: CS 177 Week 11 Recitation Slides

Using Dictionaries in Python

6

• 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

KEY VALUE

6

StudentID StudentName

S1 Kate

S2 Brittany

S3 Alice

Page 7: CS 177 Week 11 Recitation Slides

Creating Dictionaries

7

• 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

Page 8: CS 177 Week 11 Recitation Slides

Creating Dictionaries

8

• 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

Page 9: CS 177 Week 11 Recitation Slides

KEY in Dictionary vs. INDEX in List

99

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

Page 10: CS 177 Week 11 Recitation Slides

KEY in Dictionary vs. INDEX in List

1010

• 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

Page 11: CS 177 Week 11 Recitation Slides

Dictionary Operations

1111

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

Page 12: CS 177 Week 11 Recitation Slides

Dictionary Operations

1212

• The len function also works on dictionaries; it returns the number of key-value pairs:

>>> len(inventory)

3

Page 13: CS 177 Week 11 Recitation Slides

Dictionary Methods

1313

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

Page 14: CS 177 Week 11 Recitation Slides

Dictionaries and for loops

1414

>>> for key in inventory:

print("Value : ", inventory[key])

Value : 525

Value : 430

Value : 217

Value : 312

Page 15: CS 177 Week 11 Recitation Slides

Dictionary Example

1515

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

Page 16: CS 177 Week 11 Recitation Slides

Dictionary Example

1616

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

>>>

Page 17: CS 177 Week 11 Recitation Slides

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

17

Page 18: CS 177 Week 11 Recitation Slides

Tuples

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

18

Page 19: CS 177 Week 11 Recitation Slides

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

19

StudentID StudentName

S1 Kate

S2 Brittany

S3 Alice

Page 20: CS 177 Week 11 Recitation Slides

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

20

Page 21: CS 177 Week 11 Recitation Slides

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

21

Page 22: CS 177 Week 11 Recitation Slides

Tuples as Return Valuesdef 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

22

Page 23: CS 177 Week 11 Recitation Slides

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

23

Page 24: CS 177 Week 11 Recitation Slides

QUESTIONS?

2424