Python Dictionary get() Method With Examples

Python Dictionary get

Now, we are going to have a look at the get method. As the name of the method says, using the get method, we are able to get some value corresponding to the key, if the key is there in the dictionary, else we are going to get the default value.

Well, if we want to get the value corresponding to some key, we can make use of the get method here. Alternatively, we have another way, in which, we do something that is similar to accessing the list element, where we write the reference variable name, followed by the square brackets, in which, we are putting the key, whose value is required by us.

But, in this case, if the key that we are trying to access is not present in the dictionary, then it causes problems. We are going to run into errors.

But, using the get method for the same thing, is going to save us from errors. If we are using the get method for the same thing, then instead of getting an error, we would get some default value, which can be given by us as an argument to the method, and if not given, then the default value is taken as None.

Python Dictionary get() Method

Let’s now have a look at the program, where we are trying to make use of the get method, to get the corresponding value for the specified key.

As you can see in the above program, we are having a simple dictionary, and then we are trying to get some value corresponding to some key and to do that, we are making use of the get method. Basically, with the get method, we get the value corresponding to the key, if the key is there in the dictionary. Else, we get the default value, which can be specified with the get method, as an argument.

Now, if you try to run the above program, the output we get is the default value, instead of an error, since the specified key is not there in the dictionary. We have given the default value, so the default value is returned. Now, if you try giving such a key as an argument to the get method, which is present in the dictionary, then the corresponding value would be returned instead of some default value.

So, as and when required, you can make use of the get method, to get the value corresponding to the key, if the key is present. Else, you are going to get the default value.