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 vassi07

vassi07 on June 8, 2023

Hi there did someone solve this challenge?

Avatar image for Corbin Nexus

Corbin Nexus on July 15, 2023

May I suggest that Real Python include a solution video for the challenge they create so that we easy can check if we get stuck. To say that we should ask here is not that smart since it can take over a month to get a reply like in this case.

Vassi07, im sure you have solved it by now, but here is a solution that worked for me.

captains = {
    'Enterprise': 'Picard',
    'Voyager': 'Janeway',
    'Defiant': 'Sisko',
}
    # List of keys to check if they are in the dictionary
ships_to_check = ['Enterprise', 'Discovery']
    # Iterate over each key
for ships in ships_to_check:
    # Check if key is in the dictionary. If not, add it with the value 'unknown'
    if ships not in captains:
        captains[ships] = 'unknown'

print(captains)
Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on July 17, 2023

@Corbin Nexus Thanks for the comment. You’re not the first to voice a similar suggestion, so we’ve listened and are working on the solution videos as we speak.

If you still have questions, don’t hesitate to put them here. Someone will usually respond within a business day, as we regularly keep an eye on new comments.

Avatar image for JEX

JEX on July 19, 2023

Hi, if you stuck, guess that’s the right sollution.

# 1 - 2
captains = {
    'Enterprise': 'Picard',
    'Voyager': 'Janeway',
    'Defiant': 'Sisko',
}
# 3
if 'Enterprise' not in captains.keys():
    captains['Enterprise'] = 'unknown'

if 'Discovery' not in captains.keys():
    captains['Discovery'] = 'unknown'

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

# 5
del captains['Discovery']
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

Become a Member to join the conversation.