CS 177 Week 11 Recitation Slides
11
Dictionaries, Tuples
Announcements
22
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
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/19/23
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/19/23
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
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
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
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’
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
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}
Dictionary Operations
1212
• The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory)
3
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]
Dictionaries and for loops
1414
>>> for key in inventory:
print("Value : ", inventory[key])
Value : 525
Value : 430
Value : 217
Value : 312
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
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
>>>
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
Tuples
A tuple consists of a number of values separated by commas, surrounded by () (x, y) coordinate pairs Student records in the database
18
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
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
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
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
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
QUESTIONS?
2424