English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Função do Python

Tipos de dados do Python

Python file operations

Python objects and classes

Python date and time

Python advanced knowledge

Python reference manual

Python dictionary pop() usage and example

Python dictionary methods

The pop() method deletes the dictionary given key key and its corresponding value, and returns the value to be deleted. The key value must be given. Otherwise, return the default value.

The syntax of the pop() method is

dictionary.pop(key[, default])

pop() parameters

The pop() method takes two parameters:

  • key -The key to be deleted

  • default -When the key is not in the dictionary, the returned value will be

pop() return value

The pop() method returns:

  • If the key is found-Delete from the dictionary/Popped element

  • If the key is not found-Set the value to the second parameter (default value)

  • If the key is not found and no default parameter is specified- raise KeyError exception

Example1: Pop an element from the dictionary

# Random sales dictionary
sales = {'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('apple')
print('The popped element is:', element)
print('The dictionary is:', sales)

When running this program, the output is:

The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}

Example2: Pop an element that does not exist in the dictionary

# Random sales dictionary
sales = {'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('guava')

When running this program, the output is:

KeyError: 'guava'

Example3: Pop an element that does not exist in the dictionary (provide a default value)

# Random sales dictionary
sales = {'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('guava', 'banana')
print('The popped element is:', element)
print('The dictionary is:', sales)

When running this program, the output is:

The popped element is: banana
The dictionary is: {'apple': 2, 'orange': 3, 'grapes': 4}

Python dictionary methods