Python Dictionary pop() Method



The Python dictionary pop() method is used to remove an item with the specified key from a dictionary and return its value.

It works in the following way −

  • You provide the pop() method with a key as its argument.
  • If the key exists in the dictionary, the method removes the key-value pair from the dictionary and returns the corresponding value.
  • If the key does not exist, the method raises a KeyError (unless a default value is provided as the second argument, in which case it returns that default value instead of raising an error).

Syntax

Following is the basic syntax of the Python Dictionary pop() method −

dictionary.pop(key[, default])

Parameters

This method accepts the following parameters −

  • key − This is a required parameter representing the key whose associated value is to be removed and returned from the dictionary.

  • default (optional) −If the specified key is not found in the dictionary, the pop() method returns the default value. If the default parameter is not provided and the key is not found, a KeyError exception is raised.

Return Value

The method returns the value associated with the specified key.

Example 1

In the following example, we remove the key 'b' from the dictionary "my_dict" and retrieve its corresponding value −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print("The value is:",value)  
print("The dictionary obtained is:",my_dict)  

Output

The output obtained is as follows −

The value is: 2
The dictionary obtained is: {'a': 1, 'c': 3}

Example 2

Here, we try to remove the key 'd' from the dictionary "my_dict". Since the key is not present, it returns the default value "0" instead of raising a KeyError −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('d', 0)
print("The value is:",value)  
print("The dictionary obtained is:",my_dict)  

Output

Following is the output of the above code −

The value is: 0
The dictionary obtained is: {'a': 1, 'b': 2, 'c': 3}

Example 3

In this example, we remove the key 'b' from the dictionary "my_dict" and assigns its corresponding value to the variable "value" −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print("The value is:",value)    

Output

The result produced is as shown below −

The value is: 2

Example 4

Now, we try to remove the key 'd' from the dictionary "my_dict", which raises a KeyError because the key is not present in the dictionary −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('d')

Output

We get the output as shown below −

Traceback (most recent call last):
  File "/home/cg/root/660e6943bb2bb/main.py", line 2, in <module>
value = my_dict.pop('d')
KeyError: 'd'
python_dictionary_methods.htm
Advertisements