|
4 | 4 |
|
5 | 5 | # Exercise 1
|
6 | 6 | # Create an empty dictionary
|
7 |
| -birthdays = {} |
| 7 | +captains = {} |
8 | 8 |
|
9 | 9 |
|
10 | 10 | # Exercise 2
|
11 | 11 | # Add some key-value pairs to the dictionary
|
12 |
| -birthdays["Luke Skywalker"] = "5/25/19" |
13 |
| -birthdays["Obi-Wan Kenobi"] = "3/11/57" |
14 |
| -birthdays["Darth Vader"] = "4/1/41" |
| 12 | +captains["Enterprise"] = "Picard" |
| 13 | +captains["Voyager"] = "Janeway" |
| 14 | +captains["Defiant"] = "Sisko" |
15 | 15 |
|
16 | 16 |
|
17 | 17 | # Exercise 3
|
18 |
| -# Check if "Yoda" and "Darth Vader exist; if not, add them |
19 |
| -if "Yoda" not in birthdays: |
20 |
| - birthdays["Yoda"] = "unknown" |
21 |
| -if "Darth Vader" not in birthdays: |
22 |
| - birthdays["Darth Vader"] = "unknown" |
| 18 | +# Check if "Enterprise" and "Discovery" exist; if not, add them |
| 19 | +if "Enterprise" not in captains: |
| 20 | + captains["Enterprise"] = "unknown" |
| 21 | +if "Discovery" not in captains: |
| 22 | + captains["Discovery"] = "unknown" |
23 | 23 |
|
24 | 24 | # Bonus points: you could instead loop over a list of names to check
|
25 |
| -# for name in ["Yoda", "Darth Vader"]: |
26 |
| -# if not name in birthdays: |
27 |
| -# birthdays[name] = "unknown" |
| 25 | +# for name in ["Enterprise", "Discovery"]: |
| 26 | +# if not ship in captains: |
| 27 | +# captains[ship] = "unknown" |
28 | 28 |
|
29 | 29 |
|
30 | 30 | # Exercise 4
|
31 | 31 | # Display the contents of the dictionary, one pair at a time
|
32 |
| -for name in birthdays: |
33 |
| - print(name, birthdays[name]) |
| 32 | +for ship, captain in captains.items(): |
| 33 | + print(f"The {ship} is captained by {captain}.") |
34 | 34 |
|
35 | 35 |
|
36 | 36 | # Exercise 5
|
37 |
| -# Remove "Darth Vader" |
38 |
| -del (birthdays["Darth Vader"]) |
39 |
| -print(birthdays) |
| 37 | +# Remove "Discovery" |
| 38 | +del captains["Discovery"] |
40 | 39 |
|
41 | 40 |
|
42 | 41 | # Exercise 6 (Bonus)
|
43 | 42 | # Create dictionary by passing a list to dict()
|
44 |
| -birthdays = dict( |
| 43 | +captains = dict( |
45 | 44 | [
|
46 |
| - ("Luke Skywalker", "5/25/19"), |
47 |
| - ("Obi-Wan Kenobi", "3/11/57"), |
48 |
| - ("Darth Vader", "4/1/41"), |
| 45 | + ("Enterprise", "Picard"), |
| 46 | + ("Voyager", "Janeway"), |
| 47 | + ("Defiant", "Sisko"), |
49 | 48 | ]
|
50 | 49 | )
|
0 commit comments