Your program now associates surfers and their scores, but it displays the data from the hash in some sort of random ordering. You need to somehow sort the data in the hash to find out who actually won the contest.
Python hashes don't have a sort() method...
In Python, hashes are optimized for speedy insertions and even speedier look-ups (searches). As a consequence, the good folks that created Python were less interested in providing a method to sort a hash, so they didn't bother.
...but there is a function called sorted()
Obviously, there's a need to sort a hash so, again, the good folks that created Python decided to provide a really smart built-in function that has the ability to sort any data structure, and they called their function sorted () . Here's how to use the sorted () function with your hash:
Use the "sortedO" function to sort the keys of the "scores" hash.
Yo II f,nd s,m,lar desian and implementatie la?r 'p^ oi programming languages. People are different., and so ar, the programming languages they Create-
Remember: the keys in your hash are the scores, which are numbers, s° we ask "sortedO" to order them high^-to-lowest using "reverse = True •
for each_score in sorted(scores.keys(), reverse print('Surfer ' + scores[each_score] + ' scored ' + each_score)
That's one small change to one line at the bottom of your program. So, let's go ahead and make that change. Now that you are sorting the keys of the hash (which represent the surfer's scores), it should be clear why the scores were used as the key when adding data into the hash: you need to sort the scores, not the surfer names, so the scores need to be on the left side of the hash (because that's what the built-in sorted () function works with).
Was this article helpful?