IT 117: Intermediate Scripting
Class 5
Tips and Examples
New Material
Graded Quiz
You can connect to Gradescope to take weekly graded quiz
today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
You can only take this quiz today.
There is not makeup for the weekly quiz because Gradescope does not permit it.
Readings
If you have the textbook read Chapter 9, Dictionaries and Sets
section 9.1, Dictionaries.
Homework 3
I have posted homework 3
here.
It is due this coming Sunday at 11:59 PM.
Graded Quiz
You can connect to Gradescope to take weekly graded quiz
today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
You can only take this quiz today.
There is not makeup for the weekly quiz because Gradescope does not permit it.
>
Late Penalty
You will lose 2 points for every day that your assignment is late.
Every Unix file has a time stamp that changes every time the file is modified
I look at this time stamp to determine whether a submission is late.
If your assignment is not working by the due date, you can continue to work on it
but you will lose a few points.
If your assignment is working, do not go back and change it, because that will
change the time stamp and result in a late penalty.
Do Not Email Me about Missing Assignments
If you get an email from me saying an assignment is missing
do not email me about this.
I get far too many emails.
Instead of sending me an email, fix the problem.
If you do not know how to fix it, post a question on Piazza or contact the Class Assistant.
I collect homework assignments and and check Class Exercises several times during the week.
I will check or collect your assignment later in the week.
Class Exercises
Scripts for each Class Exercise must have the correct name and be in
the right directory or my scripts will not see them.
If my scripts do not see them, your score with be zero.
If you receive no email from me about your Class Exercise script, that means
your script will get full credit, less any late penalty that applies.
Tips and Examples
Read the Homework Assignments Carefully
- Homework assignments may ask you to do many things
- So you may need to read the assignment more than once
- A single reading might not be enough to understand what I want you to do
- Take the time to read these documents slowly
- This will help you understand all the details
- If you don't, you will make mistakes and lose points
- Technical work is detailed work
- So you must learn to read documents with a lot of detail
- If you do not understand something post a question on Piazza
- NEVER GUESS at the meaning of something I have written
New Material
Sequences
- Sequences
are Python
objects
that hold more than one value
- The values are stored one right after the other
- So the elements in a sequence have a definite order
- In IT 116 you encountered three types of sequences
- A list contains a series of values that can be changed at any time
- A tuple is also a series of values but a tuple is
immutable
- That means it cannot be changed
- A string is a sequence of characters which cannot be changed
- But you can make a new string from a previously created string
- Strings also have special methods that only make sense when applied to characters
- Such as capitalize
Dictionaries
- Dictionaries
can also contain multiple entries
- But each entry has two parts
- The first part is the
key
- The second is a value associated with that key
- You use the key to get the value
- An entry in a Python dictionary is a key-value pair
Dictionary Literals
- When you create a list literal you enclose the individual values in square
brackets, [ ]
- And put commas between the values
numbers = [1, 2, 3, 4, 5]
- With tuples the values are enclosed in parentheses,
( )
- Again, commas separate the values
numbers = (1, 2, 3, 4, 5)
- When we create strings we enclose them in single or double quotes
numbers = "12345"
name = 'Bob'
- In a dictionary literal we enclose the entries inside curly braces,
{ }, with commas between the entries
- In each entry, there is a colon, :, between the key and the value
email_addresses = {"Chris":"chris57@gmail.com" , "Alan":"ahurley175@yahoo.com", "Frank":"frank27@hotmail.com"}
- While keys are often strings they can be values of many different
data types
- So we could create a dictionary of integers and the words for the same value
integer_words = {1:"one", 2:"two", 3:"three", 4:"four", 5:"five"}
Empty Dictionaries
- A special kind of dictionary literal is an empty dictionary
- We often create a list by starting with an empty list and then add entries to it
- Similarly, we often create a dictionary by starting out with an empty dictionary
- Just as the empty list is represented by [ ]
- And an empty tuple is represented by ( )
- { } is an empty dictionary
Getting Values from a Dictionary
- How do we get the value associated with a key?
- To get a value from a list we put an
index
inside square brackets, [ ]
>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[0]
1
>>> numbers[1]
2
>>> numbers[4]
5
- The square brackets are actually an
operator
- When used with lists the square bracket operator takes two
operands
- A list variable and an index
- The operator gives us the value at that index position
- You can use the square bracket operator with a dictionary
- But we use the key not an index number inside the brackets
- So to get the email address for "Chris" I would write
>>> email_addresses["Chris"]
'chris57@gmail.com'
- And to get the email address for "Frank" I would write
>>> email_addresses["Frank"]
'frank27@hotmail.com'
- We don't use indexes to get the values from a dictionary as we do with lists, tuples, and strings
- Instead we use the key to get the value
- If you use the [ ] operator on a key the doesn't exist you will get a KeyError exception
email_addresses["Waldo"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Waldo'
- In computer science, a dictionary is sometimes called an associative array or a map or a hash
Changing a Dictionary Value
- You change an element in a list using [ ] and the
assignment operator
- Like this
>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[0] = 83
>>> numbers
[83, 2, 3, 4, 5]
- We can use the square bracket operators to do the same thing with dictionaries
>>> email_addresses
{'Alan': 'ahurley175@yahoo.com', 'Frank': 'frank27@hotmail.com', 'Chris': 'chris57@gmail.com'}
>>> email_addresses["Alan"] = "alan.hurley@gmail.com"
>>> email_addresses
{'Alan': 'alan.hurley@gmail.com', 'Frank': 'frank27@hotmail.com', 'Chris': 'chris57@gmail.com'}
Dictionaries Are Not Sequences
- I started out this discussion by talking about sequences
- But dictionaries are not sequences
- Sequences store a single value
- And the values are stored one right after the other
- So you can pick out a specific value using an index
- Which specifies its position in the sequence
- Dictionaries use a
data structure
called a
hash table
- Hash tables minimize the time it takes to find the value for a key
- The order of things in a hash table changes with time
- As entries are created and deleted
- In earlier version of Python 3 you could see this
- Because the order in which dictionary entries were created
- Was not the order in which they appeared when printed
- This has changed
- So dictionaries work different in the latest versions of Python
- The order in which entries are made is now the order in which they are now printed
- But dictionaries are still not sequence
Looping Through a Dictionary
- The Python
for
loop has the following format
for LOOP_VARIABLE in LIST_LIKE_THING:
STATEMENT
STATEMENT
...
- Where the LOOP_VARIABLE is assigned each value in the
LIST_LIKE_THING
- For each pass through the loop
>>> nonsense
('foo', 'bar', 'bletch')
>>> for word in nonsense:
... print(word)
...
foo
bar
bletch
>>> for number in [1, 2, 3, 4, 5]:
... print(number)
...
1
2
3
4
5
>>> for char in "Hello":
... print(char)
...
H
e
l
l
o
- But dictionaries are not sequences
- So you might think that dictionaries cannot be used with
for
loops
- But you would be wrong
>>> for entry in email_addresses:
... print(entry)
...
Chris
Frank
Alan
- In a
for
loop on a dictionary the loop variable does not get the value of the elements
- Instead, each of the keys is assigned to the loop variable
- And we can use these keys to get each value
>>> for key in email_addresses:
... print(key, "=", email_addresses[key])
...
Chris = chris57@gmail.com
Frank = frank27@hotmail.com
Alan = ahurley175@yahoo.com
Tuples As Dictionary Values
- What if I wanted to store more than one piece of information as the value for
a given key?
- For example, say I wanted to create a dictionary with data for each student in
a class
- The key would be the student ID
- But I would need to store the following data
- First name
- Last name
- Unix username
- Email
- Why first name and last name instead of just a student's name?
- Because I want to produce alphabetical lists
- To store this information do I need 4 dictionaries?
- No
- I can store all this in one dictionary using the student ID as the key
- The value will be a tuple containing all data about the student
- At the beginning of the semester I used to create a text file with data for each student
- The file looked something like this
09329034 Jane Adams jadams Jane.Adams001@umb.edu
03687480 Alexander Smith bigboy Alexander.Smith002@umb.ed
05431692 Christopher Cannon ccannon Christopher.Cannon001@umb.edu
07511379 Joseph Malloney jmal Joseph.Malloney003@umb.edu
07511379 Fatih Jones fjones Fatih.Jones001@umb.edu
04175276 James Reynolds jr jim.reynolds002@umb.edu
- This is not real student data
- Confidentiality prevents me from doing that
- Here is a function that will read each line and return dictionary with the student information
def student_dictionary_create(filename):
try:
file = open(filename,"r")
except:
print("Cannot open", filename)
else:
data = {}
for line in file:
data_list = line.split()
student_id = data_list[0]
first_name = data_list[1]
last_name = data_list[2]
username = data_list[3]
email = data_list[4]
student_tuple = (first_name, last_name, username, email)
data[student_id] = student_tuple
return data
- When I use this function and print the results
student_data = student_dictionary_create("student_data.txt")
for id in student_data:
student_tuple = student_data[id]
print(id, student_tuple[0], student_tuple[1], student_tuple[2], student_tuple[3])
- I get
09329034 Jane Adams jadams Jane.Adams001@umb.edu
03687480 Alexander Smith bigboy Alexander.Smith002@umb.ed
05431692 Christopher Cannon ccannon Christopher.Cannon001@umb.edu
07511379 Fatih Jones fjones Fatih.Jones001@umb.edu
04175276 James Reynolds jr jim.reynolds002@umb.edu
When To Use a Dictionary
- When should we use a dictionary instead of a list or tuple?
- Lists and tuples are used when the elements are not particularly unique
- If we create a list of quiz scores there is nothing special about a particular score
- Generally I don't need to know the score for the 5th quiz
- I need to have a place to put all the scores so I can do certain things
- Like finding the average score
- But every student is different
- Each one has a unique identity
- When you need to store information about unique things you should use a
dictionary
- Or when you need to associate two things
- Like a name and an email address
Attendance
Graded Quiz
Class Exercise
Class Quiz