Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Testing Yourself With a Challenge

Avatar image for alphafox28js

alphafox28js on Nov. 15, 2023

I was not sure how the comparators would work with the .keys method, but it seems to have do the job.

print("----Starship Commanders Method 1----")
1) Call Time Function: To witness processing speed.
import time
start_time = time.time()
2) Define Class Captains: Ships: Captain of Ship
captains = {
    'Enterprise': "Tiberius",
    'Voyager': "Janeway",
    'Defiant': "Sisko",
}
3) If ‘Ship’ Comparator is equal to, or not equal to, define as such.
if "Enterprise" == captains.keys():
    captains['Enterprise'] = "Unknown"
if "Discovery" != captains.keys(): #can also us if 'str' <not in> class.keys(): in replacement of <!= or ==>
    captains['Discovery'] = 'Unknown'
4)For Loop States that for it iterates through the ships, and list the captains of the ship accordingly. Personally I was not a fan of this part simply because ship was never defined anywhere. ship,captain was a lucky guess on my end after about an hour of pounding my head on this.
for ship,captain in captains.items():
    print(f"The {ship} is Captained by {captain}.")
5) Deletes the ship Discovery from the dictionary after it has already been defined as having an “Unknown Captain”…
del captains['Discovery']
6) Outputs Processing Speed.
print("Process Finished --- %s seconds ---" % (time.time() - start_time))
Avatar image for Steinar Martinussen

Steinar Martinussen on Dec. 13, 2023

I see most suggestions here use <dict_name>.keys() for interacting with the dictionary in the if statements. It works without as well. Is it considered best practise to use the dicttionary method like .keys() ?

For me this works equally well:

captains = {}
captains.update({"Enterprise": "Picard"})
captains.update({"Voyager": "Janeway"})
captains.update({"Defiant": "Sisko"})

if "Enterprise" not in captains:
    captains.update({"Enterprise": "unknown"})

if "Discovery" != captains:
    captains.update({"Discovery": "unknown"})

I also like to see the different variations that creates the same results, but I’ve stuck to the actual challenge tasks i.e start with creating an empty list, then add entries one by one.

Avatar image for Philipp Acsany

Philipp Acsany RP Team on Dec. 14, 2023

Hi Steinar! Usually, you’d check for the existence of a key in a dictionary without the .keys() method as it is a little bit more performant.

But if your dictionary is not too big, I personally like to use .keys() because it’s more explicit.

If you really want to dive deep into the topic, then you can check out How to Iterate Through a Dictionary where similar questions are answered.

Thanks for also sharing your code. Using the .update() method multiple times is a reasonable way to have control about what you add to a dictionary.

Note however, that you’re not checking for the existence of a key in this if statement:

if "Discovery" != captains:
    captains.update({"Discovery": "unknown"})

In this code, you’re checking if the string "Discovery" is not equal to the captains dictionary. The conditional statement returns False, too. That’s why the code inside the if statement is executed. But the condition is a “false positive” and can have unexpected outcomes:

captains = {
    "Defiant": "Sisko",
}

if "Defiant" != captains:
    captains.update({"Defiant": "unknown"})

print(captains)

Can you guess how captains looks in the end?

Avatar image for Steinar Martinussen

Steinar Martinussen on Dec. 15, 2023

Thanks for your quick replies Philipp. The not equal operator was something I saw in a different suggestion. And I now understand that it worked for me because I didn’t have the key ;) My own solution was using the ‘not in’ check. Will go through the lesson you suggest to delve deeper into the Dictionary use.

Avatar image for Mark Pearson

Mark Pearson on Dec. 23, 2023

As a newbie, even having done the course on IF statements, I was pretty much stuck from the beginning. While I appreciate everyone’s suggestions here, it would be great if the RP team could include the “best practice” solution to the challenge.

Avatar image for Martin Breuss

Martin Breuss RP Team on Jan. 3, 2024

@Mark Pearson we have a complete exercises course coming out soon. It’ll go over all the exercises and offer possible solutions so you can work alongside the instructor to solve them. The course is in recording at the moment and should come out soon.

Avatar image for Bebop

Bebop on Jan. 14, 2024

Great exercise to help hammer home the lessons! Here is what I came up with, with my notes too where I know I messed up. I feel like I did the “set to unknown” part wrong, any thoughts? Code works so I guess it’s right

# Real python dictionary challenge
captains = {
    "Enterprise": "Picard",
    "Voyager": "Janeway",
    "Defiant": "Sisko"
}
if "Enterprise" not in captains:
    captains["Enterprise"] = "unknown"
elif "Discovery" not in captains:
    captains["Discovery"] = "unknown"

for ship, captain in captains.items(): # This line gives the keys the value of ship, and the values the value of captain
    print(f'The {ship} is captained by {captain}')
del captains["Discovery"]
captains
Avatar image for Bebop

Bebop on Jan. 14, 2024

Terribly sorry I’m not sure how to format my code to share on forums and comments sections like this. I’m looking into it.

# Real python dictionary challenge
captains = {
    "Enterprise": "Picard",
    "Voyager": "Janeway",
    "Defiant": "Sisko"
}
if "Enterprise" not in captains:
    captains["Enterprise"] = "unknown"
elif "Discovery" not in captains:
    captains["Discovery"] = "unknown"

for ship, captain in captains.items(): # This line gives the keys the value of ship, and the values the value of captain
    print(f'The {ship} is captained by {captain}')
del captains["Discovery"]
captains

Figured it out! sorry for the spam

Avatar image for Odysseas Kouvelis

Odysseas Kouvelis on March 20, 2025

>>> _ = [print(f"The {key} is captained by {value}.") for key, value in captains.items()]
Avatar image for vmartinez

vmartinez on Nov. 12, 2025

#1.
captain = {}

print(type(captain))
print('---------#1 Done----------')

#2.

captain = {'Enterprise' : 'Picard'}
captain ['Voyager'] = 'Janeway'
captain ['Defiant'] = 'Sisko'

print(captain)
print('---------#2 Done----------')

#3.


if 'Enterprise' not in captain:
    captain ['Enterprise'] = 'unknown'
    print (captain)
else:
    print(f"'Enterprise' is in captain dictionary")

if 'Discovery' not in captain:
    captain ['Discovery'] = 'unknown'
    print (captain)
else:
    print(f"'Discovery' is in captain dictionary")

print('---------#3 Done----------')

#4.
for ships, captains in captain.items():
    print(f'The {ships} is captained by {captains}.')

print('---------#4 Done----------')

#5.
del captain['Discovery']
print(captain)
print('---------#5 Done----------')

Become a Member to join the conversation.