Python Dictionary setdefault() Method with Example

Python Dictionary setdefault

Now, we are going to learn about the setdefault method. If we want to access the element of the dictionary, we can do it very easily, using the setdefault method. Using the setdefault method, we get the value of the element corresponding to the specified key, if the key is present. But if the key is not there in the dictionary, then the key will be inserted in the dictionary, with a given value. The value would be given with the key, as another argument to the setdefault method.

Giving the value argument is optional. If the value is not given, then the default value would be considered as None.

Don’t worry if this seems too much. With an example, things will get clear.

Python Dictionary setdefault() method

Let’s have a look at an example, through which, we can better understand the setdefault method.

In the above example, we again have a sample dictionary (you can consider your own example, but we have considered a simple example over here, to understand the method in a better way).

We have called the setdefault method, with the first argument as the key, which is ‘four’. You can clearly see in the dictionary, that this key is not there in the dictionary there.

Since we are using the setdefault method, and the key ‘four’ is not there in the dictionary, the key is inserted with the specified value. So, the key ‘four’ is now inserted in the dictionary, with the value 4. Remember that if the value wasn’t there, then the default value would be considered, which is None.

Also, the return value from the setdefault method is the value of the key. As you can see, we get 4 as the returned value.

What if the key is there in the dictionary? Well, in such a situation, we are going to get the value corresponding to the existing key only. Let’s have a look at the program, which tries to demonstrate the same.

As you can see, in the above program, we have given such a key here, which is there in the dictionary. In such a situation, we get the corresponding key, which is already there in the dictionary. You can also try to execute the above program and check the output as well. So, as and when required, we can make use of the setdefault method in our python programs.