Download presentation
Presentation is loading. Please wait.
Published byCorey Owens Modified over 9 years ago
1
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 1 Introduction to Computer Programming Chapter 5: Lists and Dictionaries Michael Scherger Department of Computer Science Kent State University
2
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 2 Contents Using Lists List Methods Tuples vs Lists Nested Sequences Shared References Using Dictionaries Hangman Game
3
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 3 Hangman Example: Hangman
4
October 17, 2005ICP: 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
5
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 5 Hero’s Inventory 3.0 Program Example: Hero’s Inventory 3.0
6
October 17, 2005ICP: 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 = []
7
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 7 Using Lists Creating a List anylist = [] chevycars = [“Corvette”, “Aveo”, “Malibu”, “Cobalt”, “Impala”, “Silverado”, “Trailblazer”, “Tahoe”, “Colorado”, “Suburban”] Length Function num_cars = len( chevycars ) in Operator if “Corvette” in chevycars: print “That’s a nice car!!!!”
8
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 8 Using Lists Indexing print chevycars[4] Slicing print chevycars[0:4] Concatenation chevycars += [ “SSR”, “Monte Carlo”, “Avalanche”, “Equinox”, “Blazer”, “Astro”, “Uplander”, “Venture” ]
9
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 9 Using Lists Lists are mutable –The elements in a list can change value Change by assignment xmaslist[0] = “Black Corvette with optional blonde” xmaslist[1] = “Trip to Las Vegas” Change by slicing inventory[4:6] = “Orb of Future Telling”
10
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 10 Using Lists Deleting a list element del inventory[2] Deleting a list slice del inventory[4:6]
11
October 17, 2005ICP: 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
12
October 17, 2005ICP: 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.
13
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 13 List Methods Example: High Scores Program
14
October 17, 2005ICP: 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.)
15
October 17, 2005ICP: 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
16
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 16 Nested Sequences Row 0 Row 1 Row 2 Column 1Column 0Column 2Column 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]
17
October 17, 2005ICP: 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”)))
18
October 17, 2005ICP: 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
19
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 19 Nested Sequences 1.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. print 12. 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 are 1 2 3 4 5 6 Values in table2 by row are 1 2 3 4 5 6 This list has two rowsThis tuple has three rowsA nested for loop is needed to display all of the items in the list
20
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 20 Nested Sequences Example Example: High Scores 2.0 Program
21
October 17, 2005ICP: 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!
22
October 17, 2005ICP: 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'] >>>
23
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 23 Shared References “khakis”“dress shirt”“jacket” mike mr_scherger honey
24
October 17, 2005ICP: 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'] >>>
25
October 17, 2005ICP: 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
26
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 26 Dictionaries Example: Geek Translator
27
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 27 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
28
October 17, 2005ICP: 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
29
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 29 Dictionaries # create and print an empty dictionary emptyDictionary = {} print "The value of emptyDictionary is:", emptyDictionary # create and print a dictionary with initial values grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } print "\nAll grades:", grades # access and modify an existing dictionary print "\nSteve's current grade:", grades[ "Steve" ] grades[ "Steve" ] = 90 print "Steve's new grade:", grades[ "Steve" ] # add to an existing dictionary grades[ "Michael" ] = 93 print "\nDictionary grades after modification:" print grades # delete entry from dictionary del grades[ "John" ] print "\nDictionary grades after deletion:" print grades Alters and displays the new grade for Steve Creates an empty dictionaryAdds 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
30
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 30 Dictionaries The value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76 Steve'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}
31
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 31 Dictionaries
32
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 32 Dictionaries
33
October 17, 2005ICP: 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]}
34
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 34 Dictionaries monthsDictionary = { 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 dictionaryPrints out just the values in the dictionaryLoops though using the keys to display all the items in the dictionary
35
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 35 Dictionaries The 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 ] = January monthsDictionary[ 2 ] = February monthsDictionary[ 3 ] = March monthsDictionary[ 4 ] = April monthsDictionary[ 5 ] = May monthsDictionary[ 6 ] = June monthsDictionary[ 7 ] = July monthsDictionary[ 8 ] = August monthsDictionary[ 9 ] = September monthsDictionary[ 10 ] = October monthsDictionary[ 11 ] = November monthsDictionary[ 12 ] = December
36
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 36 Hangman Program Again Example: Hangman
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.