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

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary pop() usage and example

Dictionary methods in Python

The pop() method deletes the dictionary given key key and the 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

The pop() return value

The pop() method returns:

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

  • If the key is not found-Specify the value as the second parameter (default value)

  • If the key is not found and no default parameter is specified- Trigger 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 the 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 the 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 the program, the output is:

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

Dictionary methods in Python