Python Dictionary pop
Now, we are going to learn about the pop method. The pop method helps us remove the specified element from the dictionary. This method returns the value of the removed element. We have to specify what element needs to be removed. Let’s have a look at the program, which would help us better understand the pop method →
Python Dictionary pop() method
As you can see, we have the dictionary, and then we are calling the pop method, and we have passed the key, as ‘two’. As the pop method executes, the element with the key ‘two’ is removed, and the returned value from the method is the value from that element. After that, we are printing the dictionary again, and we find that the element that we gave as an argument to the pop method is removed. We directly printed the output from the pop method, but you can store it somewhere as per the requirement.
So, as and when required, we can make use of the pop method in our program. Remember that the pop method is going to remove the element according to the given key, and it is going to return the value corresponding to the given key.
Note that if we are giving such a key to the pop method, which is not there in the dictionary, in such a situation, we are going to get the default value, which can be provided as the second argument to the method. Have a look at the below program, which demonstrates the same.
As you can see in the above program, we have specified such a key to the pop method, which is not there in the dictionary. But as a second argument, we are providing the default value. So, if the specified key is not there in the dictionary, and we have specified the default value as an argument, we would get the default value as the argument. You can try executing the program and observing the output as well.
On the other hand, if we have not given the default value as well, and we are just specifying the key to the pop method as an argument, then we are going to get an error. Here is the program for the same.
As you can see in the above program, we have specified such a key, that is not there in the dictionary. Also, we have not specified the second argument, which is the default value. In such a situation, we are going to get into error.
So, as and when required, we can make use of the pop method in the python programs. Remember that this method removes the element according to the specified key-value pair.