Python Tutorial Python Advanced Python References Python Libraries

Python Dictionary - pop() Method



The Python pop() method deletes a specified key-value pair of the dictionary. This method has a optional parameter which is used to return value if specified key is not present. In the absence of this parameter, an exception will be raised if the key is not found in the dictionary.

Syntax

dictionary.pop(key, default)

Parameters

key Required. value of the element which need to be counted in the list.
default Optional. returns value if specified key is not present in the dictionary.

Return Value

Returns the value of the deleted key of the dictionary.

Example: pop() without optional parameter

In the example below, pop() method is used to delete city and hobby keys. As hobby key is not present in the dictionary, it will raise an exception.

Info = {
  'name': 'John',
  'age': 25,
  'city': 'London'
}

Info.pop('city') 
print(Info)     
Info.pop('hobby') 
print(Info)

The output of the above code will be:

{'name': 'John', 'age': 25}

Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    Info.pop('hobby') 
KeyError: 'hobby'

Example: pop() with optional parameter

To handle exception discussed in above example, optional parameter can be used. Deleted key or returned value can be accessed through method object.

Info = {
  'name': 'John',
  'age': 25,
  'city': 'London'
}

method_object = Info.pop('city', 'key is not found.')
print(method_object)   
print(Info, "\n")   
method_object = Info.pop('hobby', 'key is not found.') 
print(method_object)
print(Info)

The output of the above code will be:

London
{'name': 'John', 'age': 25}

key is not found.
{'name': 'John', 'age': 25}

❮ Python Dictionary Methods