Skip to content

Commit bdc6108

Browse files
committed
Update solutions to dictionary exercises
1 parent 432aa30 commit bdc6108

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

ch09-lists-tuples-and-dictionaries/6-store-relationships-in-dictionaries.py

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,47 +4,46 @@
44

55
# Exercise 1
66
# Create an empty dictionary
7-
birthdays = {}
7+
captains = {}
88

99

1010
# Exercise 2
1111
# 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"
1515

1616

1717
# 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"
2323

2424
# 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"
2828

2929

3030
# Exercise 4
3131
# 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}.")
3434

3535

3636
# Exercise 5
37-
# Remove "Darth Vader"
38-
del (birthdays["Darth Vader"])
39-
print(birthdays)
37+
# Remove "Discovery"
38+
del captains["Discovery"]
4039

4140

4241
# Exercise 6 (Bonus)
4342
# Create dictionary by passing a list to dict()
44-
birthdays = dict(
43+
captains = dict(
4544
[
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"),
4948
]
5049
)

0 commit comments

Comments
 (0)