Python Dictionary pop() Method Tutorial

In this section, we will learn what the Dictionary pop() method is and how to use it in Python.

What is Dictionary pop() Method in Python?

The Python Dictionary pop() method is used to remove the specified key (set as the first argument of this method) from the target Dictionary.

Python Dictionary pop() Method Syntax:

dictionary.pop(key, defaultValue)

Dictionary pop() Method Parameter:

The method takes two arguments:

  • The first argument is the key that we want it to be removed from the target Dictionary.
  • The second argument, which is optional, is a default value that will be returned if the target Dictionary didn’t have the specified key.

Dictionary pop() Method Return Value

The return value of this method is the value of the key that we set as the argument of the method to be removed from the dictionary.

Note: if the dictionary didn’t have the specified key, then the return value of this method will be the second argument of the method. But if no value set as the second argument, then the method will throw an exception.

Example: using python dictionary pop() method

dictionary = {

"name":"John",

"lastName":"Doe"

}

print(dictionary.pop("age",0))

Output:

0

Note that here we didn’t have a key with the name “age” in the target dictionary. So for this reason, the method returned the value set as the second argument of this method.

Leave a Reply