Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Hashes and databases. File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31.

Similar presentations


Presentation on theme: "Chapter 5 Hashes and databases. File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31."— Presentation transcript:

1 Chapter 5 Hashes and databases

2 File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31

3 Who won the surfing contest? scores=[ ] result_f=open(“results.txt”) for line in result_f: (name, score)=line.split() scores.append(float(score))result_f.close()scores.sort(reverse=True) print(“The top scores are: “) ??? print(scores[0])print(scores[1])print(scores[2])

4 Rewrite the program scores=[ ] names=[ ] result_f=open(“results.txt”) for line in result_f: (name, score)=line.split() scores.append(float(score))names.append(name)result_f.close()scores.sort(reverse=True)names.sort(reverse=True) print(“The top scores are: “) ??? print(names[0]+’ with ‘ +str(scores[0])) print(names[1]+’ with ‘ +str(scores[1])) print(names[2]+’ with ‘ +str(scores[2]))

5 Associate name and score NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31 Need a different data structure!!!

6 Hash A variable that has exactly two columns and (potentially) many rows of data key – value A data structure that associates a name with a value Other names in different programming languages: mappingdictionary association array key-value list

7 Using a hash # Start with an empty hash: scores={} # Add data # Put the key inside the square brackets # put the value to the right of the assignment op scores[8.45]=‘Joseph’ # New row of data is added to the hash # No explicit “append()” method like arrays

8 Using a hash Can use a for loop to iterate over each of the rows in a hash: for key in scores.keys(): print(scores[key]+’ had a score of ‘+str(key)) keys() – built-in method that returns an array of the keys of the hash. values() – built-in method that returns an array of the values of the hash.

9 Using a hash Use the square brackets to refer to a value associated with a key: print(scores[9.12]) items() – Another hash method that returns key-value pair. (one can use it with the for loop) for score,surfer in scores.items(): print(surfer + ‘ had a score of ‘ + str(score))

10 The new program scores={}result_f=open(‘results.txt’) for line in result_f: (name,score)=line.split() ??? scores[score]=nameresult_f.close() print(“The top scores were”) for each_score in scores.keys(): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

11 Sorting data in a has No sort() method BUT There is a function called sorted() sorted() – bulit-in function that has the ability to sort any data structure for each_score in sorted(scores.keys(),reverse=True): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

12 The new program scores={}result_f=open(‘results.txt’) for line in result_f: (name,score)=line.split() Hurray!!! scores[score]=nameresult_f.close() print(“The top scores were”) for each_score in sorted(scores.keys(), reverse=True): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

13 When data gets complex Data file (competition id, name, country, average score, board type, age): 101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21 102;Juan Martino;Spain;9.01;Gun;36 103;Joseph 'smitty' Smyth;USA;8.85;Cruizer;18 104;Stacey O'Neill;Ireland;8.91;Malibu;22 105;Aideen 'board babe' Wu;Japan;8.65;Fish;24 106;Zack 'bonnie-lad' MacFadden;Scotland;7.82;Thruster;26 107;Aaron Valentino;Italy;8.98;Gun;19 Problem: Find and display a surfer’s data based on competition ID

14 Printing surfer’s data line=“101;Johnny ‘wave-boy’ Jones;USA;8.32;Fish;21” Display: ID:101 Name:Johnny ‘wave-boy’ Jones Country:USA Average:8.32 Board type:Fish Age:21

15 Printing surfer’s data line=“101;Johnny ‘wave-boy’ Jones;USA;8.32;Fish;21” s={}#create an empty hash (s[‘id’],s[‘name’],s[‘country’],s[‘average’].s[‘board’],s[‘age’])=line.split(“,”) print(“ID:“+s[‘id’]) print(“Name:“+s[‘name’]) print(“Country:“+s[‘country’]) print(“Average:“+s[‘average’]) print(“Board type:“+s[‘board’]) print(“Age:“+s[‘age’])

16 Processing ALL lines in data file Problem: Write a function that takes the surfer ID as a parameter, searches the file one line at a time for a matching ID, and then returns the found data to the caller. How to return the data ??? 1. as a string 2. as a hash Which one should we use???

17 Processing ALL lines in data file Problem: Write a function that takes the surfer ID as a parameter, searches the file one line at a time for a matching ID, and then returns the found data to the caller. How to return the data ??? 1. as a string 2. as a hash Which one should we use??? Answer: A hash – It allows the calling code to simply pick out the information it needs without further processing.

18 find_details function def find_details(id2find): surfers_f=open(“surfing_data.csv”) for each_line in surfers_f: s={}(s[‘id’],s[‘name’],s[‘country’],s[‘average’].s[‘board’],s[‘age’])=line.split(“,”) if id2find == int (s[‘id’]): surfers_f.close()return(s)surfers_f.close() return ({})

19 Testing the function lookup_id=int(input(“Enter the id of the surfer: “)) surfer=find_details(lookup_id) if surfer: print(“ID:“+s[‘id’]) print(“Name:“+s[‘name’]) print(“Country:“+s[‘country’]) print(“Average:“+s[‘average’]) print(“Board type:“+s[‘board’]) print(“Age:“+s[‘age’])

20 Using data from a database import sqlite3 def find_details(id2find): db = sqlite3.connect("surfersDB.sdb") db.row_factory = sqlite3.Row cursor = db.cursor() cursor.execute("select * from surfers") rows = cursor.fetchall() for row in rows: if row['id'] == id2find: s = {} s['id'] = str(row['id']) s['name'] = row['name'] s[ 'country'] = row['country'] s['average'] = str(row['average']) s['board'] = row['board'] s['age'] = str(row['age']) cursor.close() return(s) cursor.close() return({})


Download ppt "Chapter 5 Hashes and databases. File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31."

Similar presentations


Ads by Google