Page 323 - Beginning Programming with Pyth - John Paul Mueller
P. 323
dictionary.
5. Type the following code pressing Enter after each line, and then
click Run Cell.
for Item in Colors.keys(): print("{0} likes the color {1}."
.format(Item, Colors[Item]))
The example code outputs a listing of each of the user names and the user’s favorite color, as shown in Figure 14-8. Using dictionaries can make creating useful output a lot easier. The use of a meaningful key means that the key can easily be part of the output.
6. Type Colors[′′ Sarah′′] =′′Purple′′ and press Enter.
The dictionary content is updated so that Sarah now likes Purple instead of Yellow.
7. Type Colors.update({′′ Harry′′: ′′ Orange′′}) and press Enter. A new entry is added to the dictionary.
8. Typethefollowingcode,pressingEnteraftereachline: for name, color in Colors.items():
print("{0} likes the color {1}." .format(name, color))
Compare this code to the code in Step 5. This version obtains each of the items one at a time and places the key in name and the value in color. The output will always work the same from the item() method. You need two variables, one for the key and another value, presented in the order shown. The reason to consider this second form is that it might be easier to read in some cases. There doesn't seem to be much of a speed difference between the two versions.
9. Click Run Cell.
You see the updated output in Figure 14-9. Notice that Harry is
added in sorted order. In addition, Sarah’s entry is changed to the color Purple.
10. Type del Colors[′′ Sam′′] and press Enter. Python removes Sam’s entry from the dictionary.
11. Repeat Steps 8 and 9.