October 17, 2005ICP: Chapter 5: Lists and Dictionaries 1 Introduction to Computer Programming...
-
Upload
corey-owens -
Category
Documents
-
view
213 -
download
0
Transcript of October 17, 2005ICP: Chapter 5: Lists and Dictionaries 1 Introduction to Computer Programming...
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
1
Introduction to Computer Programming
Chapter 5: Lists and Dictionaries
Michael Scherger
Department of Computer Science
Kent State University
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
2
Contents
• Using Lists
• List Methods
• Tuples vs Lists
• Nested Sequences
• Shared References
• Using Dictionaries
• Hangman Game
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
3
Hangman
• Example: Hangman
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
4
Introduction
• Data structures– Structures that hold and organize information
• Sequences– Also know as arrays in other languages– Store related data types– 3 types
• Strings• Lists• Tuples
• Mappings– In most languages called hashes or associative arrays– Dictionaries are the only python mapping container
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
5
Hero’s Inventory 3.0 Program
• Example: Hero’s Inventory 3.0
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
6
Creating Sequences (Review)• Strings
– Use quotes– string1 = ""
• Tuples– Use parenthesis– Separate multiple items with a comma– tuple = ()– singleton = 1, - this is a one element tuple or a singleton
• Lists– Use brackets– Separate multiple items with a comma– list1 = []
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
7
Using Lists
• Creating a Listanylist = []chevycars = [“Corvette”, “Aveo”, “Malibu”, “Cobalt”, “Impala”, “Silverado”, “Trailblazer”, “Tahoe”, “Colorado”, “Suburban”]
• Length Functionnum_cars = len( chevycars )
• in Operatorif “Corvette” in chevycars:print “That’s a nice car!!!!”
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
8
Using Lists
• Indexingprint chevycars[4]
• Slicingprint chevycars[0:4]
• Concatenationchevycars += [ “SSR”, “Monte Carlo”, “Avalanche”, “Equinox”, “Blazer”, “Astro”, “Uplander”, “Venture” ]
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
9
Using Lists
• Lists are mutable – The elements in a list can change value
• Change by assignmentxmaslist[0] = “Black Corvette with optional blonde”
xmaslist[1] = “Trip to Las Vegas”
• Change by slicinginventory[4:6] = “Orb of Future Telling”
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
10
Using Lists
• Deleting a list elementdel inventory[2]
• Deleting a list slicedel inventory[4:6]
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
11
List Methods
• append(value)– Adds value to the end of the list
• sort()– Sorts the elements, smallest value first
• reverse()– Reverses the order of a list
• count(value)– Returns the number of occurences of value in the list
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
12
List Methods
• index(value)– Returns the first position number of where value occurs
• insert(i, value)– inserts value at position i
• pop([i])– Returns value at position i and removes value from the list.
Providing the position number is optional. Without it, the last element in the list is removed.
• remove(value)– Removes the first occurrence of value from the list.
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
13
List Methods
• Example: High Scores Program
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
14
Tuples vs. Lists
• Tuples are faster than lists. Because the computer knows they will not change, tuples can be stored in a way that makes using them faster that using lists. For simple programs, this speed difference will not matter, but in more complex applications, with very large sequences of information, it could.
• Tuples’ immutability makes them perfect for creating constants since they cannot change. Using tuples can add a level of safety and clarity to your code.
• Sometimes tuples are required. In some cases Python requires immutable values. (Example shown later when Dictionaries are discussed.)
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
15
Nested Sequences
• Tuples and Lists can be sequences of anything– Including other tuples and lists
• Nested Sequences– Sequences inside other sequences– A great method to organize complex collections of
information
• Common use is a table– By convention it is organized by row and column
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
16
Nested Sequences
Row 0
Row 1
Row 2
Column 1Column 0 Column 2 Column 3
a[0][0] a[0][3]a[0][1] a[0][2]
a[1][0] a[1][3]a[1][1] a[1][2]
a[2][0] a[2][3] a[2][2]
Column index (or subscript)
Row index (or subscript)
Array name
a[2][1]
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
17
Nested Sequences
• Creating nested sequences (examples)
nested_1 = [“first”, (“second”, “third”), [“fourth”, “fifth”, “sixth” ]]
scores = [(“Moe”, 1000),(“Larry”, 1500),(“Curly”, 2000)]
nested_2 = (“deep”,(“deeper”,(“deepest”,”still deepest”)))
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
18
Nested Sequences
• Accessing Nested Sequences (example)>>> scores = [(“Moe”, 1000),(“Larry”, 1500),(“Curly”, 2000)]>>> print scores[0](‘Moe’, 1000)>>> print scores[1](‘Larry’, 1500)>>> print scores[2](‘Curly’, 2000)
>>> a_score = scores[2]>>> print a_score(‘Curly’, 2000)>>> print a_score[0]Curly
>>> print scores[2][0]Curly>>> print scores[2][0][4]y
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
19
Nested Sequences1. table1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]2. table2 = ( ( 1, 2 ), ( 3, ), ( 4, 5, 6 ) )3. 4. print "Values in table1 by row are"5. 6. for row in table1:7. 8. for item in row:9. print item,10. 11. print12. 13. print "\nValues in table2 by row are"14. 15. for row in table2:16. 17. for item in row:18. print item,19. 20. print
Values in table1 by row are1 2 34 5 6
Values in table2 by row are1 234 5 6
This list has two rows
This tuple has three rows
A nested for loop is needed to display all of the items in the list
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
20
Nested Sequences Example
• Example: High Scores 2.0 Program
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
21
Shared References• Consider the following
example…s = “Python”
• The variable s refers to a place in memory where the string value “Python” is stored.
• A variable refers to a value the same way a person’s name refers to a person. It would be wrong to say that a person’s name “stores” the person. Using a person’s name you can get to the person. Using a variable’s name you can get to a value.
“Python
s
• For lists, when several variables refer to the same mutable value, they share the same reference!
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
22
Shared References>>> mike = ['khakis', 'dress shirt', 'jacket']>>> mr_scherger = mike>>> honey = mike>>> print mike['khakis', 'dress shirt', 'jacket']>>> print mr_scherger['khakis', 'dress shirt', 'jacket']>>> print honey['khakis', 'dress shirt', 'jacket']>>>
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
23
Shared References
“khakis” “dress shirt” “jacket”
mike
mr_scherger
honey
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
24
Shared References>>> mike = ['khakis', 'dress shirt', 'jacket']>>> mr_scherger = mike>>> honey = mike>>> print mike['khakis', 'dress shirt', 'jacket']>>> print mr_scherger['khakis', 'dress shirt', 'jacket']>>> print honey['khakis', 'dress shirt', 'jacket']>>> >>> >>> honey.append('brown shoes')>>> print mike['khakis', 'dress shirt', 'jacket', 'brown shoes']>>>
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
25
Dictionaries
• Programmers love to organize information– Lists and tuples organize things into
sequences
• Dictionaries stores information in pairs– Similar to an actual dictionary
• Word and definition• Python uses key and value
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
26
Dictionaries
• Example: Geek Translator
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
27
Dictionaries
• Dictionaries– Mapping constructs consisting of key-value
pairs• Referred to as hashes in other languages
– Unordered collection of references– Each value is referenced though key in the
pair
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
28
Dictionaries
– Curley braces ({}) are used to create a dictionary
– When entering values• Use { key1:value1, … }
– Keys must be immutable values such as strings, numbers and tuples
– Values can be of any Python data type
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
29
Dictionaries# create and print an empty dictionaryemptyDictionary = {}print "The value of emptyDictionary is:", emptyDictionary # create and print a dictionary with initial valuesgrades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 }print "\nAll grades:", grades # access and modify an existing dictionaryprint "\nSteve's current grade:", grades[ "Steve" ]grades[ "Steve" ] = 90print "Steve's new grade:", grades[ "Steve" ] # add to an existing dictionarygrades[ "Michael" ] = 93print "\nDictionary grades after modification:"print grades # delete entry from dictionarydel grades[ "John" ]print "\nDictionary grades after deletion:"print grades
Alters and displays the new grade for Steve
Creates an empty dictionary
Adds a new name to the grades dictionary
Removes the name john from the dictionary with the del keyword
Creates a grades dictionary using names as the key and their grade as the value
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
30
DictionariesThe value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76Steve's new grade: 90 Dictionary grades after modification:{'Edwin': 89, 'Michael': 93, 'John': 87, 'Steve': 90, 'Laura': 92} Dictionary grades after deletion:{'Edwin': 89, 'Michael': 93, 'Steve': 90, 'Laura': 92}
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
31
Dictionaries
Method Description
clear() Deletes all items from the dictionary.
copy() Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary).
get( key [, returnValue] ) Returns the value associated with key. If key is not in the
dictionary and if returnValue is specified, returns
the specified value. If returnValue is not specified,
returns None.
has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is
not in the dictionary.
items() Returns a list of tuples that are key-value pairs.
keys() Returns a list of keys in the dictionary.
popitem() Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a Key-Error exception occurs. [Note: We discuss
exceptions in Chapter 12, Exception Handling.] This method is useful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary.
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
32
Dictionaries
setdefault( key [, dummyValue] )
Behaves similarly to method get. If key is not in the dictionary and dummyValue is specified, inserts the key and the specified value into dictionary. If
dummyValue is not specified, value is None.
update( newDictionary ) Adds all key-value pairs from newDictionary to the current dictionary and overrides the values for keys that already exist.
values() Returns a list of values in the dictionary.
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
33
Dictionaries>>> dictionary = { "listKey" : [ 1, 2, 3 ] }>>> shallowCopy = dictionary.copy() # make a shallow copy>>> dictionary[ "listKey" ].append( 4 )>>> print dictionary{'listKey': [1, 2, 3, 4]}>>> print shallowCopy{'listKey': [1, 2, 3, 4]} >>> from copy import deepcopy>>> deepCopy = deepcopy( dictionary ) # make a deep copy>>> dictionary[ "listKey" ].append( 5 )>>> print dictionary{'listKey': [1, 2, 3, 4, 5]}>>> print shallowCopy{'listKey': [1, 2, 3, 4, 5]}>>> print deepCopy{'listKey': [1, 2, 3, 4]}
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
34
DictionariesmonthsDictionary = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July", 8 : "August", 9 : "September", 10 : "October", 11 : "November", 12 : "December" } print "The dictionary items are:"print monthsDictionary.items() print "\nThe dictionary keys are:"print monthsDictionary.keys() print "\nThe dictionary values are:"print monthsDictionary.values() print "\nUsing a for loop to get dictionary items:" for key in monthsDictionary.keys(): print "monthsDictionary[", key, "] =", monthsDictionary[ key ]
Creates a dictionary with the month number as the key and the month name as the value
Prints out all the items, both key and value, in the dictionary
Prints out all the keys in the dictionary
Prints out just the values in the dictionary
Loops though using the keys to display all the items in the dictionary
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
35
DictionariesThe dictionary items are:[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10,
'October'), (11, 'November'), (12, 'December')] The dictionary keys are:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] The dictionary values are:['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Using a for loop to get dictionary items:monthsDictionary[ 1 ] = JanuarymonthsDictionary[ 2 ] = FebruarymonthsDictionary[ 3 ] = MarchmonthsDictionary[ 4 ] = AprilmonthsDictionary[ 5 ] = MaymonthsDictionary[ 6 ] = JunemonthsDictionary[ 7 ] = JulymonthsDictionary[ 8 ] = AugustmonthsDictionary[ 9 ] = SeptembermonthsDictionary[ 10 ] = OctobermonthsDictionary[ 11 ] = NovembermonthsDictionary[ 12 ] = December
October 17, 2005 ICP: Chapter 5: Lists and Dictionaries
36
Hangman Program Again
• Example: Hangman