11.7. Accumulating Results From a Dictionary¶
Just as we have iterated through the elements of a list to accumulate a result, we can also iterate through the keys in a dictionary, accumulating a result that may depend on the values associated with each of the keys.
For example, suppose that we wanted to compute a Scrabble score for the Study in Scarlet
text. Each occurrence of the letter ‘e’ earns one point, but ‘q’ earns 10. We have
a second dictionary, stored in the variable
letter_values. Now, to compute the
total score, we start an accumulator at 0 and go through each of the letters in the
counts dictionary. For each of those letters that has a letter value (no points for spaces,
punctuation, capital letters, etc.), we add to the total score.
Line 18 is the tricky one. We are updating the variable tot to have its old number plus the score for the current letter times the number of occurrences of that letter. Try changing some of the letter values and see how it affects the total. Try changing txt to be just a single word that you might play in Scrabble.
Check your Understanding
1. The dictionary
travel contains the number of countries within each continent that Jackie has traveled to. Find the total number of countries that Jackie has been to, and save this number to the variable name
total. Do not hard code this!
schedule is a dictionary where a class name is a key and its value is how many credits it was worth. Go through and accumulate the total number of credits that have been earned so far and assign that to the variable
total_credits. Do not hardcode.