IT 117: Intermediate Scripting
Class 5
General Advice
Course Work
Tips and Examples
New Material
Microphone
Questions
Are there any questions before I begin?
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.
Today's Class
Today I will talk about dictionaries, a new
king of object that holds multiple values and can be very
useful.
General Advice
Learn to Read Carefully
- Most of us spend a large part of each day reading
- Most of this reading is done quickly ...
- because the material is familiar ...
- and the details are not that important
- Most of the time when we read, we know what to expect
- For example, if you get a text from a friend ...
- you don't linger over each word
- You have some idea of what your friend is going to say ...
- so you can read it quickly
- The same thing happens if you read the about your favorite singer
- The details aren't important ...
- just the overall picture
- The reading you must do for this course ...
- is fundamentally different
- Technical work is detailed work
- If you read technical material too quickly ...
- you will miss important details
- You must learn to read technical material slowly and carefully
- You will sometime have to read something a second or third time ...
- until you fully understand it
- Learning how to read technical material ...
- may be the most important thing you take away from this class
Course Work
Graded Quiz Today
- After I finish my lecture today I will hand out papers for today's
graded quiz
- Write your name clearly at the top
- When you finish the Quiz hand it to me
- Then you can work on the Class Exercise
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
- My scripts look at this date 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
- Any changes you make will change the date stamp ...
- which will cost you points
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
- Come to Zoom Office Hours
- Post a question of Piazza
- Contact the Class Assistant
- I collect homework assignments and check Class Exercises several times during the week
- I will check or collect your assignment later in the week.
Importance of Exams
- Many people 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
Do Not Fall Behind in This Course
- Technical courses require that you master a great deal of detail
- You will need to study for this course several times during the week
- Studying once a week is usually not enough
- The key to success in a technical course is steady, consistant, work
- It should be spread out over several days
- Some important concepts do not sink in immediately
- It may take several days for something new to become clear
- Material in this course often depends on what came before
- So it is critical that you not fall behind
- If you fall behind, it can be VERY hard to catch up
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 in memory 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"}
- In the first entry, "Chris" is the key ...
- and "chris57@gmail.com" is the value
- 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 variable pointing to a list 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 = {}
- To add value to a list we use the
append method
- But dictionaries have no methods to add entries
- Instead you create a new entry in a dictionary using
[ ] ...
- with a new key
- Notice that I said a new key
- Here is an example
>>> 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}
- 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
- I took me a long time to get use to this ...
- when I first started using dictionaries
Changing a Dictionary Value
- You change an element in a list using [ ] ...
- with an index number inside the brackets ...
- 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
- The values in a sequence 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 differently in the latest versions of Python
- The order in which entries are made ..
- is now the order in which they are printed
- But that order is not the order in which the entries are stored ...
- in RAM
- So dictionaries are still not sequence
- I'll talk more about this in the next class
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
- You can use a
for loop with tuples
>>> nonsense
('foo', 'bar', 'bletch')
>>> for word in nonsense:
... print(word)
...
foo
bar
bletch
- With lists
>>> for number in [1, 2, 3, 4, 5]:
... print(number)
...
1
2
3
4
5
- And strings
>>> 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
- When running a
for loop on a dictionary ...
- the loop variable does not get the value of the elements
- Instead, the loop variable gets the value of each key
- Of course we can use these keys to get their associated 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 data in one dictionary using the student ID as the key
- But the value will be a tuple containing all information 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 you don't need to know the score for the 5th quiz
- But you do need a single object to hold all the scores ...
- so you 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