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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Loop Over the Dictionary (Solution)

00:00 Now you need to loop over the dictionary. And there is one important part with this exercise here, and that’s that you want to print the key and the value at the same time.

00:12 So you don’t just care about the values or just the keys, but you want both at the same time. And that’s where the .items() dictionary method comes handy in place.

00:23 You start with for loop and then you refer to the key and the value in your for loop definition. And there you can use the variable names just like you want in this case, ship and captain because I mean you can use what you want, but it should make sense.

00:40 So here it’s the ship and the captain from our dictionary, which are the keys and the values in captains. That’s the dictionary.

00:49 And then you use the .items() dictionary method. And this dictionary method gives you back a tuple with the key and the value for each for loop step, which then is the ship and the captain string.

01:04 And then you can print in the next line inside the for loop’s body, you can create an f-string with

01:12 the, and then you add in the ship variable with curly braces. The curly brace ship closing curly brace is captained by, and then again curly braces captain.

01:32 And then quote to close the string and the closing parentheses. So there you print an f-string. Again, the variables that you format into the string are ship and captain, which are the variables that you defined in your for loop definition.

01:47 So if you named your variables differently, then in the f-string you would refer to different variables. So here ship is the key, which I defined and captain will be the value.

01:59 And when you press enter, you can see the output of the print() function call, which is the enterprise is captained by Picard. The voyager is captained by Janeway and the defiant is captained by Sisko.

02:13 And then last but not least, the discovery is captained by unknown.

Become a Member to join the conversation.