IT 117: Intermediate Scripting
Class 5
Course Work
Tips and Examples
New Material
Microphone
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.
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.
Questions
Are there any questions before I begin?
Course Work
Importance of Exams
- I know that many of you find exams difficult
- But the best way for me to know if you have really learned
the material is by giving exams
- It is too easy to cheat on Class Exercises and homework assignments
- This is why the two exams account for 50% of your grade
- Too many students do well on the graded quizzes, Class Exercises
and homework assignment ...
- only to do poorly on the exams
- This lowers their grade considerably
- The purpose of the Class Exercises and homework assignments
is to give you hands on experience with the material
- And to better prepare you for the exams
Preparing for Exams
- Both the midterm and final exams follow the same format
- 60% of the points on the exams come from questions taken
from the ungraded class quizzes
- The remaining 40% of the points come from 4 code questions
- These questions ask you to write short segments of Python
code
- Two things will help you prepare for exams
- Flash cards
- Class Exercises and homework assignments
- Flash cards should be made for all questions from Ungraded
Class Quizzes
- You should review them frequently throughout the semester
- Pay attention when you are working on the Class Exercises and
homeworks
- Work on these assignments is teaching you how to write Python code
- This will come in handy for answering the code questions on
the midterm and final
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
Attendance
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
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 integer value
integer_words = {1:"one", 2:"two", 3:"three", 4:"four", 5:"five"}
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 that
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
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 adding 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
Adding Entries to a Dictionary
- Just as with lists, there are two ways to create a directory
- Use a dictionary literal
- Add entries to an empty dictionary
- The second method is more common
- We define an empty dictionary like this
email_addresses = {}
- Dictionaries have no methods to add entries to an existing dictionary
- Instead you use the [ ] operator to create an entry
- You create a new entry in a dictionary using [ ] with a new key
>>> email_addresses = {} # create empty dictionary
>>> email_addresses["Alan"] = "alanh@gmail.com" # add first entry
>>> email_addresses["Chris"] = "chrisk@yahoo.com" # add second entry
>>> email_addresses # print the dictionary
{"Chris": "christhek@gmail.com", "Alan": "alanh@gmail.com"}
- Here is another example
>>> words_integers = {}
>>> words_integers["one"] = 1
>>> words_integers["two"] = 2
>>> words_integers["three"] = 3
>>> words_integers["four"] = 4
>>> words_integers["five"] = 5
>>> words_integers
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
- But you have to be careful when adding entries like this
- You have to make sure that the key you use for the new entry
- is not already in the dictionary
- If the key is already in use you will not add a new entry
- You will just change the value associated with the old key
- So adding entries to a dictionary is very different from adding to a list
- When adding to a list we use the list method append
- But there no dictionary method for creating a new entry
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'}
- Note that the way you add an entry to a dictionary ...
- is the same way you change an entry in a dictionary
- They both have the same format
DICTIONARY_VARIABLE[KEY] = EXPRESSSION
- If the KEY is already in the dictionary ...
- the value associated with it will be changed
- Otherwise the dictionary will get a new entry
- We use the same [ ] operator to add an entry ...
- as we used to change the value of an entry
- When I first started using dictionaries I found this confusing
- When you see a Python statement like this
>>> words_integers["six"] = 6
- It could either mean I have created a new entry ...
- or I've changed an existing entry ...
- whose key is "six"
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 that order is not the order in which the entries are stored
- So 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
- But 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
Class Exercise
Class Quiz