Check the Existence of Keys (Solution)
00:00
It’s good that this exercise asks you to do two if
statements because then I can show you two solutions to this exercise with each if
statement.
00:12
So to check if a key exists in a dictionary, you can write if
and then the name is a key. For example, the enterprise
string not in
.
00:25
If you want to check if a key is not in a dictionary, you use the not in
if
statement. And if you want to check if a key is in a dictionary, you just write for example if enterprise in dictionary_name
.
00:37
So in this case we want to check if the key is not in the dictionary, so we use not in
, and the dictionary name is captains
.
00:48
And then on the next line, you want to set the value of enterprise
to unknown
if it doesn’t exist. So similar to a formal lesson, you write captains
and then square brackets, then the key enterprise
closing square bracket equals, and then it should equal the string unknown
if it doesn’t exist.
01:14
And once you press enter and enter again, we can check the captains
dictionary if the key existed or not and was overwritten with unknown
.
01:25
And as you can see, it’s still become
because the key existed. So the if
statement returned false and didn’t put the value unknown
to the key enterprise
.
01:35
Another way to check if a key exists in a dictionary or if a key doesn’t exist in a dictionary, you can write a similar statement but with the .keys()
method.
01:45
In the end, let me show you how this looks. If
and this time we want to check if
01:54
discovery not in captains
.keys()
, colon. And then on the next line, similar like before this time, the ship name is discovery
.
02:07
So you set captains['discovery']
again to unknown
if the key discovery
doesn’t exist in the captains
dictionary.
02:21
Again, let’s check how captains
looks. And now you can see that discovery
was added to the dictionary with the value unknown
.
02:32 Generally, you might use the first variant. There is a subtle difference between it, which shouldn’t bother you that much right now. But just so you know, there are different ways of doing it.
02:43 Both are fine for now. I prefer the first one, but it’s up to you.
Become a Member to join the conversation.