Week 11 Recitation - Purdue CS Wiki/Application server

Download Report

Transcript Week 11 Recitation - Purdue CS Wiki/Application server

CS 177 Week 11 Recitation
Slides
Dictionaries, Tuples
1
1
Announcements
2
2
Why Do We Use Dictionary 1/3
•
•
Suppose we have the following table, that associates an
identifier to a student name:
StudentID
StudentName
S1
S2
Kate
Brittany
S3
Alice
This association is a relationship between the identifier
and the student name
3
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:
–
–
–
–
–
4/2/2016
–
>>> myList[0]
['S1', 'Kate']
>>> myList[0][1]
'Kate‘
>>> myList[0][0]
'S1'
CS177 - Spring 2011
4
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
4/2/2016
CS177 - Spring 2011
5
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
KEY
StudentID
StudentName
S1
S2
Kate
Brittany
S3
Alice
VALUE
6
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
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
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
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
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
Dictionary Operations
•
The len function also works on dictionaries; it returns the
number of key-value pairs:
>>> len(inventory)
3
12
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
Dictionaries and for loops
>>> for key in inventory:
print("Value : ", inventory[key])
Value :
Value :
Value :
Value :
525
430
217
312
14
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
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
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’)
StudentID
StudentName
>>>Tup2 = (‘S2’, ‘Brittany’)
S1
Kate
>>>Tup3 = (‘S3’, ‘Alice’)
S2
Brittany
S3

Alice
We can also build a tuple of tuples…
>>>StuTup = (Tup1, Tup2, Tup3)
>>>print (StuTup)
((‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’))
19
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 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
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?
24
24