Page 189 -
P. 189
iterate hash data
Iterate hash data with for
Let’s add some additional rows of data to your hash:
Scores Data in a hash is
scores[9.12] = 'Juan' Joseph maintained in a
8.45
scores[7.21] = 'Zack' seemingly random order,
7.21 Zack but don't worry about
The new rows Juan that for now.
have been added. 9.12
Once you have a hash created, you can use the trusty
for loop to iterate over each of the rows:
The “keys()" built-in method returns an array of
guessing what the “values()" method does.
T ake each of the the keys of the hash. There are no extra points for
keys in the hash
in turn...
for key in scores.keys():
print(scores[key] + ' had a score of ' + str(name_part))
...and display a custom
message using the data When referring to a value associated with a key, use
in each row of the hash. square brackets (just like you did with array data).
Here's what would
display on screen
(assuming all the
data in “results.txt”
was available to the
hash).
Another hash method, called items(), returns each key-value pair in turn,
and can be used with the for loop, too:
The “items()” method returns each
key-value pair.
for score, surfer in scores.items():
print(surfer + ' had a score of ' + str(score))
Whichever method you use to iterate over your hash’s data is up to you,
because using items() or keys() produces the same output.
154 Chapter 5