Handling Missing Keys
Welcome back! In the introductory lesson, I mentioned that what sets
dict apart from each other is mainly the way in which they handle missing keys. And also in the introductory lesson, I showed you how you use keys to assign values to dictionaries and how to retrieve them. In this lesson, we’ll go into how dictionaries handle missing keys a bit more deeply.
So, there are two ways in which dictionaries allow you to avoid
KeyError right out of the box. What sets them apart from each other is whether or not they modify the dictionary. Let me show you what I mean.
I got this last
KeyError because I looked up the value for
'b' and there is no
'b' key. However, if I use
.get() like this and enter as a first parameter the key which I’m looking for and as a second parameter a default value, then my dictionary returns
2. It returns
2 even though there is no entry for
'b'. In other words, it behaves as if an entry existed for this key, and it doesn’t error out.
If I did want to update my dictionary, I would use a different method and that’s
.setdefault(). Let me show you how that works. So, I’ll use
.setdefault(), and again, I’m entering two parameters.
The first is the key which I’m looking for, and then the second is a default value. And so far, this looks just like
.get(). After all, I didn’t get an error even though there was no entry for
'b', and my line of code returned the value
2 as if that key had been present in the dictionary.
So to sum up, there are two methods which allow dictionaries to handle missing keys gracefully—gracefully in the sense that they won’t error out. The first is
.get(), which you pass with a key you’re looking for and a value which you would like to have returned if there is no value actually assigned to that key already.
The second is
.setdefault(). It does pretty much the same thing as
.get() except it creates this key in the dictionary, and it creates an entry—so it enters the value which you provide. It doesn’t only return it to you. In both of these cases, if the key which you were looking for already existed in the dictionary, then you would just have gotten the value which was already there.
Become a Member to join the conversation.