We used the accumulator pattern to build up from an empty string or list, or to keep track of a running total.
Since dictionaries are just another type of collection, the accumulator pattern works with them as well.
We can add key/value pairs one at a time to an empty dictionary using bracket notation:
Example
Let’s create a dictionary that uses strings as key/value pairs.
1 2 3 4 5 6 7 8 | eng_to_pirate = {}
eng_to_pirate['Hello'] = 'Ahoy'
eng_to_pirate['your'] = 'yer'
eng_to_pirate['there'] = 'yonder'
eng_to_pirate['element 18'] = 'Ar'
print(eng_to_pirate)
|
Console Output
{'Hello': 'Ahoy', 'your': 'yer', 'there': 'yonder', 'element 18': 'Ar'}
In lines 3 - 6, on the left hand side of the =
operator we define the
new keys for the eng_to_pirate
dictionary. On the right hand side of the
=
, we place the value to assign to the key.
Each key is an English word, and its value is the related term in pirate-speak.
A more efficient way would be to use the accumulator pattern to add new key/value pairs. Recall that with lists and strings, the pattern adds only one new thing each time the loop repeats. For dictionaries, we need to add two items—a new key and a new value.
Let’s play with a couple of examples to practice this.
Try It!
The following program builds the vowel_count
dictionary by adding a new
key/value pair each time the loop repeats. Each character from the string
'aeiou'
becomes a key in the dictionary, which gets linked to an integer
value.
vowel_counts
.vowel_counts
. Each key is one
character from vowels
, and its value is how often that letter occurs
in the guide
string.Now try:
print
statement inside the loop. Run the
program to see how vowel_counts
grows each time the loop repeats.guide
with games
in line 7.for
statement to count different
letters or other characters. (As a good Python coder, you should change
your variable names once you stop counting vowels).The previous example took the characters from the string 'aeiou'
and turned
them into dictionary keys. We used items from one collection (a string) to help
us build a new dictionary.
The next example combines the elements of two lists into a single dictionary.
Try It!
Let’s build an English-to-pirate translation dictionary! We will use English words as keys and pirate words for the values.
Feel free to add your own words to each list! However, be sure to keep both lists the same length.
Note the following:
english_words[index]
accesses one element from the
english_words
list, and it uses that element to define a new key. For
example, the first time through the loop, the left hand side of line 9
evaluates as:eng_to_pirate[english_words[index]]
eng_to_pirate[english_words[0]]
eng_to_pirate['hello']
pirate_words
list:pirate_words[index]
pirate_words[0]
'ahoy'
eng_to_pirate['hello'] = 'ahoy'
,
and this adds the 'hello' : 'ahoy'
key/value pair to the
eng_to_pirate
dictionary.We can also use the accumulator pattern to perform an operation with the values in a dictionary.
Example
1 2 3 4 5 6 7 8 9 | exam_scores = {'exam_1' : 95, 'exam_2' : 90.7, 'exam_3' : 88.3}
total = 0
for key in exam_scores.keys():
total += exam_scores[key]
average = total / len(exam_scores)
rounded_average = round(average, 1)
print("The average result is {0}%.".format(rounded_average))
|
Console Output
The average result is 91.3%.
Note the following:
total
and assign it an
initial value of 0
.for
statement to loop through the keys of the
exam_scores
dictionary.total
by the value
linked to the current key. For example, the first time through the loop,
line 5 operates this way:total += exam_scores[key]
total += exam_scores['exam_1']
total += 95
total = total + 95
total = 0 + 95
total = 95
Question
What does the following program print?
1 2 3 4 5 6 7 8 | my_animals = {"cats":10, "dogs":5, "elephants":25, "bears":20}
total = 0
for key in my_animals:
if len(key) > 4:
total += my_animals[key]
print(total)
|
Question
We want to code an accumulator that takes names and ticket numbers from two different lists, then uses that data to add key/value pairs to a dictionary.
The names should be the keys in the dictionary with the ticket numbers as their values.
Given the following statements:
1 2 3 4 5 6 | names = ['Bob', 'Maria', 'Devon', 'Jessi']
ticket_numbers = [100, 101, 102, 103]
ticket_holders = {}
for index in range(len(names)):
# Assignment statement here.
|
which of the following is the correct syntax for adding the key/value
pairs to ticket_holders
?