Easy Tutorial
❮ Ref Set Pop Python Shellsort ❯

Python3 Dictionary pop() Method

Python3 Dictionary


Description

The Python dictionary pop() method removes the value corresponding to the specified key in the dictionary and returns the deleted value.

Syntax

The syntax for the pop() method is:

pop(key[, default])

Parameters

Return Value

Returns the deleted value:

Example

The following example demonstrates the usage of the pop() method:

#!/usr/bin/python3

site = {'name': 'tutorialpro.org', 'alexa': 10000, 'url': 'www.tutorialpro.org'}

element = site.pop('name')

print('Deleted element:', element)
print('Dictionary:', site)

Output:

Deleted element: tutorialpro.org
Dictionary: {'alexa': 10000, 'url': 'www.tutorialpro.org'}

If the key to be deleted does not exist, it triggers an exception:

#!/usr/bin/python3

site = {'name': 'tutorialpro.org', 'alexa': 10000, 'url': 'www.tutorialpro.org'}

element = site.pop('nickname')

print('Deleted element:', element)
print('Dictionary:', site)

Output:

File "/Users/tutorialpro/tutorialpro-test/test.py", line 5, in <module>
    element = site.pop('nickname')
KeyError: 'nickname'

You can set a default value to avoid the exception:

#!/usr/bin/python3

site = {'name': 'tutorialpro.org', 'alexa': 10000, 'url': 'www.tutorialpro.org'}

element = site.pop('nickname', 'Non-existent key')

print('Deleted element:', element)
print('Dictionary:', site)

Output:

Deleted element: Non-existent key
Dictionary: {'name': 'tutorialpro.org', 'alexa': 10000, 'url': 'www.tutorialpro.org'}

Python3 Dictionary

❮ Ref Set Pop Python Shellsort ❯